How Ajax cross-origin conversion works:
1. cause: the same-origin policy of the browser
2. The script can avoid the same-source policy check. Jsonp uses this principle.
Jsonp uses the <script/> label to dynamically parse JavaScript documents. (You can also use the eval function)
Here is a simple example:
HTML code
- <! Doctype HTML public "-// W3C // dtd xhtml 1.0 transitional // en" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <HTML xmlns = "http://www.w3.org/1999/xhtml">
- <Head>
- <Title> test jsonp </title>
- <SCRIPT type = "text/JavaScript">
- Function jsonpcallback (result)
- {
- Alert (result. msg );
- }
- </SCRIPT>
- <SCRIPT type = "text/JavaScript" src = "http://crossdomain.com/jsonServerResponse? Jsonp = jsonpcallback "> </SCRIPT>
- </Head>
- <Body>
- </Body>
- </Html>
Among them, jsoncallback is registered by the client. After obtaining JSON data on the Cross-origin server, it calls back the function.
Http://crossdomain.com/jsonServerResponse? Jsonp = jsonpcallback
This URL is the interface for the cross-origin server to retrieve JSON data. The parameter is the name of the callback function and the returned format is
JS Code
- Jsonpcallback ({MSG: 'This is JSON data '})
Jsonp principle:
Register a callback on the client, and then pass the callback name to the server.
In this case, the server is converted into JSON data.
Then, a function is generated in Javascript syntax. The function name is the passed parameter jsonp.
Finally, place the JSON data directly in the function as an input parameter. In this way, a JS syntax document is generated and returned to the client.
The client browser parses the script tag and executes the returned JavaScript document. As a parameter, the data is passed into the pre-defined callback function of the client. (The callback function is dynamically executed)
Other cross-origin Methods: IFRAME. Http://blog.csdn.net/coldy456/article/details/5982712