JSON and jsonp

Source: Internet
Author: User
Tags server website

Preface

Although JSON and jsonp have only one letter, they are not the same thing at all: JSON is a data exchange format, jsonp is an unofficial cross-domain data interaction protocol created by the ingenuity of developers.

What is JSON?

JSON (JavaScript Object Notation) is a lightweight data exchange format. It is based on a subset of JavaScript (Standard ECMA-262 3rd edition-December 1999. JSON

It is completely independent of the language's text format, but it also uses a habit similar to the C language family (including C, C ++, C #, Java, JavaScript, Perl, Python, etc ). These features make JSON an ideal data exchange language. Easy to human

Reading and writing are also easy for machine parsing and generation.

JSON has two structures:
JSON is simply an object and an array in Javascript. Therefore, the two structures are objects and arrays. These two structures can represent various complex structures.

1. Object: the expanded content represented as "{}" in JS. The data structure is {key: value, key: value ,...} the structure of the key-value pair. In the object-oriented language, the key is the object attribute, and the value is the corresponding attribute value, so it is easy to understand that the value method is the object. key, which can be a number, String, array, or object.

2. array: The array is expanded by brackets "[]" in JS. The data structure is ["Java", "JavaScript", "VB",...], the value can be obtained using indexes in the same way as in all languages. Field values can be of the following types: Numbers, strings, arrays, and objects.
After the object and array structures, you can combine them into complex data structures.

 JSON format or rule: 

JSON can describe the data structure in a very simple way. XML can be used to describe the data structure. Therefore, the two are completely different across platforms.
 
1. JSON only has two data type descriptors, braces {} and square brackets []. The remaining English colons are ing characters, English commas (,) are separators, and English double quotation marks (") are definitions.
 
2. braces {} are used to describe a set of "unordered key-value pairs of different types" (each key-value pair can be understood as an OOP attribute description ), square brackets [] are used to describe a group of "ordered data sets of the same type" (which can correspond to an OOP array ).
 
3. If multiple sub-items exist in the preceding two sets, they are separated by commas.
 
4. Key-value pairs are separated by a colon (:). We recommend that you add double quotation marks (") to the key names for resolution in different languages.
 
5. Common Data Types in JSON are strings, numbers, Boolean values, dates, and null. strings must be enclosed in double quotation marks, and other data types are not used. The date type is special, I will not discuss it here, but it is recommended that if the client does not need to sort by date, it is better to pass the date and time directly as a string, which saves a lot of trouble.

JSON instance

     //  Describe a person     VaR Person = {  "  Name  " : "  Aehyok  "  ,  "  Age  " : 25  ,  "  Company  " : "  Aehyok  "  ,  "  Engineer  " : True  }  //  Obtain the information of this person.      VaR Personage = Person. Age; alert (personage );  //  Describe several persons      VaR Members = [{  "  Name  " : "  Aehyok  "  ,  "  Age  " : 25  ,  "  Company  " :"  Aehyok  "  ,  "  Engineer  " : True  },{  "  Name  " : "  Lqm  "  ,  " Age  " : 25  ,  "  Company  " : "  Oracle  "  ,  "  Engineer  " : False  },{ "  Name  " : "  Thl  "  ,  "  Age  " : 22  ,  "  Company  " : "  Microsoft "  ,  "  Engineer  " : False  }]  //  Read the company name of lqm.          VaR Lqmcompany = members [ 1  ]. Company; alert (lqmcompany );  //  Describe a meeting      VaR Conference ={  "  Conference  " : "  Future Marketing  "  ,  "  Date  " : "    "  ,  "  Address " : "  Shenzhen  "  ,  "  Members  "  :[{  "  Name  " : "  Aehyok  "  , "  Age  " : 25  ,  "  Company  " : "  IBM  "  ,  "  Engineer  " : True },{  "  Name  " : "  Lqm  "  ,  "  Age  " : 25  ,  "  Company  " :"  Oracle  "  ,  "  Engineer  " : False  },{  "  Name  " : "  Thl  "  , "  Age  " : 20  ,  "  Company  " : "  Microsoft  "  ,  "  Engineer  " : False }]}  //  Whether the Thl reader is an engineer          VaR Thlisanengineer = Conference. members [ 2  ]. Engineer; alert (thlisanengineer ); 

For JSON, first come here.

Http://www.cnblogs.com/aehyok/archive/2013/05/01/3052697.html

Http://www.cnblogs.com/aehyok/archive/2013/05/18/3085499.html

Let's take a look at the above two articles.ArticleAbout how to implement jquery ajax to submit JSON data in ASP. net mvc.

What is jsonp?

1. A well-known problem is that AJAX directly requests common files without cross-domain access permissions. Render Manager determines that you are a static page, dynamic webpage, Web Service, and WCF, as long as it is a cross-domain request, no;
 
2. However, we found that when calling JS files on the web page, it is not affected by cross-origin (not only that, we also found that all tags with the "src" attribute have cross-domain capabilities, such as <SCRIPT>, , and <IFRAME> );
 
3. It can be determined that in the current stage, cross-Origin data access is only possible if you want to access data through pure web (ActiveX control, server proxy, websocket that belongs to HTML5 in the future, that is to say, on the remote server, try to put data into JS files for the client to call and further process;
 
4. We already know that there is a pure character data format called JSON that can describe complex data in a concise manner. Even better, JSON is also supported by JS native, therefore, the client can process data in this format as needed;
 
5. In this way, the solution is ready. The Web client uses the same method as the calling script to call the JS format files dynamically generated on the Cross-origin server (generally with the suffix of JSON). Obviously, the purpose of the server to dynamically generate a JSON file is to load the data required by the client.
 
6. After the client successfully calls the JSON file, it obtains the required data. The rest is to process and present the data as needed, this method of obtaining remote data looks like Ajax, but it is actually not the same.
 
7. In order to facilitate the use of data on the client, an informal transmission protocol is gradually formed, which is called jsonp. One key point of this Protocol is to allow users to pass a callback parameter to the server, then, when the server returns the data, the callback parameter is wrapped in JSON data as the function name, so that the client can customize its own function to automatically process the returned data.
 
If the callback parameter is still vague, we will introduce specific examples later.

The specific implementation of the jsonp client:

1. the simplest one. First, I set up two websites in IIS. Of course, if the port is 888 and the port is 8888, we use 888 as the local server, and 8888 as the remote server.

There is a local webpage

 
<HTML> "Text/JavaScript"Src ="Http: // localhost: 8888/remote. js"> </SCRIPT>  

The Javascript file references the remote. js file 8888.

 
Alert ('I am a Remote File');

After running the local server website, the effect is

Now the simplest cross-origin is successful.

2. Let's modify it on the basis of 1 first.Code

<HTML> "Text/JavaScript">Function aehyok (data) {alert (data. Result );}</SCRIPT> <SCRIPT type ="Text/JavaScript"Src ="Http: // localhost: 8888/remote. js"> </SCRIPT>  

Add a JS function to the local file and then call the JS file of the remote server.

Aehyok ({"Result":"Data from remote JS"});

This is the code in the remote server JS file.
Effect after running

The call is successful. It indicates that the local function is successfully called by the cross-origin remote JS, and the data from the remote JS is also received. I'm glad that the goal of cross-origin remote data retrieval is basically achieved, but another problem arises. How can I let remote JS know the name of the local function that should be called? After all, jsonp service providers have to deal with many service objects, and these service objects have different local functions? Let's look down.

<SCRIPT type = "  Text/JavaScript  " > $ (Document). Ready (function () {$. Ajax ({type:  "  Get "  ,  Async : False  , URL:  "  ../Home/aehyok  "  , Datatype:  "  Jsonp  "  , Jsonp:  "  Callback  " ,//  Pass to request processingProgramOr page to obtain the parameter name of the jsonp callback function (usually the default value is callback) Jsonpcallback: "  Aehyok  " , //  The custom jsonp callback function name. The default value is the random function name automatically generated by jquery. You can also enter "? ", Jquery will automatically process the data for you  Success: function (JSON) {alert (  "  Second  " + JSON. Result) ;}, error: function () {alert ( '  Fail  '  ) ;}}) ;}); Function aehyok (data) {alert (  "  First time  " + Data. Result );} </SCRIPT>

I am in the Asp.net mvc3.0 project, so the background is in the Controller

Public StringAehyok (){Return "Aehyok ({\ "Result \": \ "data from remote JS \"})";}

Then the execution result is

After debugging, we can find that urlhttp: // localhost: 6247/home/aehyok? Callback = aehyok & _ = 1369235398641

Callback = aehyok is the callback function. After the call is completed, aehyok (data) is executed first ).

Then execute success (JSON ). So there are two pop-up windows.

I am only working on a project now. The truth is the same.

Summary

I feel very practical. I hope I can practice it in projects in the future.

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.