JSONP cross-Domain request instance

Source: Internet
Author: User

JSONP cross-Domain request instance

There are many different ways to request across domains,

1,iframe

2,document.domain

3,window.name

4,script

5,xdomainrequest (ie8+)

6,xmlhttprequest (firefox3.5+)

7,postmessage (HTML5)

8, background Agent

...

They have their own advantages and disadvantages, the return of the data format are also different, should be carefully selected according to demand. For example, the IFRAME returned to the HTML fragment is more appropriate, the old effort to use it to return to JSON is not worth the candle. At the beginning I will build a practical cross-domain request tool Sjax. The biggest disadvantage of using a script request is error handling. For example, 404 error, it is not like XMLHttpRequest can accurately return the status code 404. I'll put this in the last article.

This series mainly describes the mode 4 above, in which JSON-formatted data data is returned via script. This way is now called JSONP. JSON is one of the most popular and widely used formats for communication between the front and back channels at present. As opposed to the early Ajax return of XML (x is XML in AJAX), JSON is lighter, there is no extra tag tag, parsing is native. XML returns to the front end and is first translated into documents through a layer of parsing of the DOM API. Parsing the DOM is expensive, especially in earlier versions of IE (IE6/7/8), and the cost of core JS communication with DOM is high.

Jsonp The realization of the idea is very simple

1, the front end creates the script tag, sets SRC, and adds it to the head (you can add it to the body).

2, the background returns a JS variable Jsonp, this JSONP is the JSON data after the request.

3, after the callback is complete, delete the script tag (there are some cleanup work such as avoiding some browser memory leaks, etc.).

Sjax.load (
URL,//cross URL of request
Success,//callback function, you must define a parameter to receive the global variable JSONP returned in the background (the contract backend returns such as Jsonp = {...}) Structure
Timestamp,//True will add a timestamp to prevent caching, default does not add
);

Instance

<! DOCTYPE html>
<meta charset= "Utf-8" >
<title>sjax_0.1.js by snandy</title>
<script src= "Http://files.cnblogs.com/snandy/sjax_0.1.js" ></script>
<body>
<p id= "P1" style= "background:gold;" ></p>
<input type= "button" value= "Get Name" onclick= "CLK ()"/>
<script type= "text/web Effects" >
function CLK () {
Sjax.load (
' Http://files.cnblogs.com/snandy/jsonp.js ',
function () {
document.getElementById (' P1 '). InnerHTML = ' Hi, ' + jsonp.name;
}
);
}
</script>
</body>

This HTML implements one of the simplest front and back interaction functions, clicking on the button "Get name" and getting to name and showing on the paragraph p.

The Sjax.load method is called in the CLK function, and the s in Sjax is the script. I used the Ajax name in my Ajax series, and here I use the sjax.

The requested background URL is jsonp.js, which returns the following
1 JSONP = {name: ' Jack '};

Because it is a test, it is implemented in the simplest way. The requested background is not necessarily a JS file, can be PHP tutorials, Java, and any background language, they may connect the database tutorial for a series of business inquiries. In short, the final return of the structure must be variable JSONP, this variable is a JS object, as to how complex there is no need to pay attention.


Add two practical features

1, add the Data property, request parameters
2, increase the scope property to allow the callback function to execute in the specified context

Sjax.load (URL, {
Data//Request parameter (key value pair string or JS object)
Success//Successful callback function
Scope//callback function execution context
Timestamp//Whether to add time stamp
});

Example

<! DOCTYPE html>
 <meta charset= "Utf-8" >
 <title> Sjax_0.2.js by Snandy</title>
 <script src= "Http://files.cnblogs.com/snandy/sjax_0.2.js" >< /script>
<body>
<input type= "button" value= "Get Name" onclick= "CLK ()"/>
& Lt;script type= "Text/javascript"
 function clk () {
  sjax.load (' http://files.cnblogs.com /snandy/jsonp.js ', {
   fn:function () {alert (jsonp.name)},
   data: {A: ' 1 ', B: ' 2 ', c:[11,22]},
   timestamp:true
  });
 }
</script>
</body>

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.