Jsonp Theory Example code detailed

Source: Internet
Author: User
Tags domain server

what is JSON?
JSON (JavaScript Object Notation) is a lightweight data interchange format. It is based on a subset of JavaScript (standard ECMA-262 3rd edition-december 1999). JSON uses
Completely language-independent text format, but also used similar to the C language family habits (including C, C + +, C #, Java, JavaScript, Perl, Python, etc.). These features make JSON an ideal data exchange language. Easy for people
Reading and writing, but also easy machine parsing and generation.
JSON has two types of structure:
JSON is simply called objects and arrays in JavaScript, so these two structures are objects and arrays of 2 structures that can represent a variety of complex structures
1, object: Object in JS expressed as "{}" the content of the expansion, data structure is {Key:value,key:value,...} The structure of key-value pairs, in object-oriented languages, key is the property of the object, value is the corresponding property value, so it is easy to understand that the value method is the object. Key Gets the property value, the type of the property value can be a number, a string, an array, several objects.
2, array: The array in JS is the middle bracket "[]" the content, data structure for ["Java", "JavaScript", "VB",...], the value way and all languages, using index get, the type of field value can be number, string, array, object several.
Through the object, the array 2 kinds of structure can be combined into a complex data structure.
The format or rule of JSON:
JSON can describe a data structure in a very simple way, and XML can do it all, so it's completely pitches in cross-platform terms.
1. JSON has only two data type descriptors, curly braces {} and square brackets [], the remaining English colons: is the map, comma, is the delimiter, the English double quotation mark "" is the definition.
2, curly braces {} are used to describe a set of "different types of unordered key-value pairs" (each key-value pair can be interpreted as an attribute description of OOP), and square brackets [] are used to describe a set of "ordered sets of data of the same type" (which corresponds to an array of OOP).
3, if there are more than one of the two sets of children, it is separated by commas.
4. The key value pairs are separated by a colon: and the key name is suggested with the English double quotation mark "" to facilitate the parsing of different languages.
5, JSON internal data type is nothing more than string, number, Boolean, date, null so several, the string must be enclosed in double quotation marks, the rest are not, the date type is special, here does not expand the narrative, but it is recommended if the client is not sorted by date function requirements, It would be nice to pass the date and time directly as a string, which would save a lot of trouble.

What is Jsonp
1, a well-known problem, Ajax directly request ordinary file There is no access to cross-domain issues, no matter you are static pages, dynamic Web pages, Web services, WCF, as long as the cross-domain requests, are not allowed;
2, but we also found that the Web page when the JS file is not affected by whether or not cross-domain impact (not only that, we also found that the "src" attribute of the label has the ability to cross-domain, such as <script>, , <iframe >);
3, so can judge, the current stage if you want to through the pure Web side (ActiveX control, Server Agent, belongs to the future of HTML5 WebSocket, etc.) access to data across domains is only one possibility, that is, on the remote server to try to load the data into the JS format of the file, For client invocation and further processing;
4, it happens that we already know that there is a kind of pure character data format called JSON can be concise description of complex data, even better is the JSON is also supported by JS native, so in the client can almost arbitrary processing of this format of data;
5, such a solution is to be seen, the Web client by the same way as the call script to invoke the cross-domain server dynamically generated JS format files (usually JSON suffix), it is obvious that the server to dynamically generate JSON files, The goal is to load the data that the client needs.
6, the client in the JSON file after the successful call, but also to obtain their own required data, the rest is to do their own needs to deal with and show that the way to get remote data looks very much like Ajax, but in fact, it is not the same.
7, in order to facilitate the use of data by the client, gradually formed an informal transport protocol, people call it Jsonp, one of the main points of the protocol is to allow users to pass a callback parameter to the server, The callback parameter is then used as the function name to wrap the JSON data when the server returns data, so that the client can customize its own function to automatically process the returned data.
If there is some ambiguity about how the callback parameter is used, there are specific examples to explain later.

JSONP Client-specific implementations :
1. First one of the simplest. First I set up two sites in IIS, of course the port one is 888 and the other one is 8888, we put 888 as the local server, 8888 as the remote server.
Now there's a local Web page

<title>index.html</title>
<script type= "Text/javascript" src= "Http://localhost:8888/remote.js" ></script>
<body></body>

Where the JavaScript file refers to the 8888 Remote.js file.

Alert (' I am a remote file ');

After you run the local server Web site, the effect is

Now the simplest cross-domain is successful.
2. We make changes on the basis of 1, first look at the code

<title>index.html</title>
<script type= "Text/javascript" >
function Aehyok (data)
{
alert (Data.result);
}
</script>
<script type= "Text/javascript" src= "Http://localhost:8888/remote.js" ></script>
<body></body>

Add a JS function to the local file first, and then call the remote server's JS file.

Aehyok ({"Result": "I am the data brought by remote JS"});

This is the code in the remote server JS file.
Post-run effects

The call succeeded. The local function is displayed by the remote JS call across the domain, and the data from the remote JS is also received. Happily, the goal of cross-domain remote data acquisition is basically realized, but another problem arises, how can I let remote JS know what the local function it should call called? After all, JSONP service providers have to face a lot of service objects, and these service objects are different local functions? We went on to look down.

<script type= "Text/javascript" >

$ (document). Ready (function () {
$.ajax ({
Type: "Get",
Async:false,
URL: ".. /home/aehyok ",
DataType: "Jsonp",
JSONP: "Callback",//passed to the request handler or page, the name of the parameter used to obtain the name of the JSONP callback function (generally by default: callback)
Jsonpcallback: "Aehyok",//Custom JSONP callback function name, default to jquery automatically generated random function name, can also write "?", jquery will automatically process the data for you
Success:function (JSON) {
Alert ("Second time" +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 string Aehyok ()

{
Return "Aehyok ({\" result\ ": \" I am the data that the remote JS brings "})";
}

Then execute the result as

urlhttp://localhost:6247/home/aehyok?callback=aehyok&_=1369235398641 can be found by debugging
The Callback=aehyok is the callback function that returns the Aehyok (data) after the call is completed.
Then execute success (JSON). So there are two of pop-up windows.

Jsonp Theory Example code detailed

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.