How jquery uses jsonp to obtain JSON data across domains (to solve jquery's cross-server permission restriction problem)

Source: Internet
Author: User

HTML code:

<HTML xmlns = "http://www.w3.org/1999/xhtml">

 

<Head runat = "server">
<Title> </title>
<SCRIPT src = "jquery-1.3.2-vsdoc2.js" type = "text/JavaScript"> </SCRIPT>
<SCRIPT type = "text/JavaScript">
Function getdata (){
$. Ajax ({
URL: "http: // 192.168.2.32/jquery/ajax_do.aspx? Callback =? ",
Datatype: "jsonp ",
Jsonp: "Callback ",
Success: function (data ){
Alert (data );
$ ("# Sp_data" ).html (data. msg );
}
});
}
</SCRIPT>
</Head>
<Body>
<Div>
<A onclick = "getdata ()" href = "#" style = "color: Blue"> Cross-origin </a>
</Div>
</Body>
</Html>

 

 

Background code (ajax_do.aspx.cs ):

 

String callback = request. querystring ["Callback"];
Response. Write (callback + "({MSG: 'error action! '})");

 

 

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)

 

 

 

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.