The three main ways of Ajax processing across domains in jquery _jquery

Source: Internet
Author: User
Tags new set script tag

Because of the influence of JS homology policy, JS can only access documents under the same domain name. So to achieve cross-domain, there are several ways to do this:

First, the way to deal with Cross-domain:

1. The Agent


The XMLHttpRequest Level2 (and XHR2) provided in HTML5 have been implemented across domain access. But ie10 below does not support

Just fill in the response header on the service side:

 Header ("access-control-allow-origin:*");
 /* Asterisk indicates that all fields are acceptable, *
 /Header ("Access-control-allow-methods:get,post");



Ajax itself is not a cross-domain,
Cross-domain by generating a script tag. Because the SRC attribute of the script label is not a cross-domain restriction.

In fact, set the datatype: ' Jsonp ' after the $.ajax method and Ajax XMLHttpRequest nothing to do with, instead of the JSONP protocol. JSONP is an unofficial protocol that allows the integration of script tags on the server side back to the client, enabling Cross-domain access through JavaScript callback.

Cross-domain notation for Ajax:

(The rest is written in the same way as not across domains):

Like what

 /* Current URL is localhost:3000*/
 js code
 $.ajax ({
 type: "Get",
 URL: "Http://localhost:3000/showAll", * URL write an exotic request address * * *
 dataType: "Jsonp", * plus datatype*/
 jsonpcallback: "CB",/* Set a callback function, name casually take, and the following function in the same name on the line * *
 success:function () {

 * * and on exotic servers,
 app.get ('/showall ', students.showall);/* This is the same as not cross-domain: *
 in the ShowAll function of the exotic server, * *

 var db = require ("./database");

 Exports.showall = function (req,res) {

 /** Set response header allows Ajax to cross domain access **/
 res.setheader ("Access-control-allow-origin" ,"*");
 * * Asterisk indicates that all foreign requests can be accepted, * *
 res.setheader ("Access-control-allow-methods", "Get,post");

 var con = Db.getcon ();
 Con.query ("SELECT * from T_students", function (error,rows) {
 if (error) {
 console.log ("Database error:" +error);
 } else{
 /* Note here, the return is the JSONP callback function name + data "* *
 Res.send (" CB ("+json.stringify (R) +)")

Ii. cross-domain approach to solving Ajax Cross-domain access and JQuery

JS Cross-domain problem, I think a lot of programmers mind inside also think that JS is not cross-domain, in fact, this is a wrong point of view; there are a lot of people on the Internet to find their solution, teaching its use of IFRAME to solve a lot of articles, really so complicated? In fact it's very simple, if you use jquery, a Getjson method is done, and a line of code is done.

Here's how to start sticking out.

Cross-domain (across all domain names)
$.getjson ("", function (JSON) { 
//requires the data format of the remote request page to be:? (json_data)//For example://? ([{"_name": "Hunan Province", "_regionid": 134},{"_name": "Beijing", "_regionid": 143}]) 

$.getjson ("", function (JSON) { 
// Requires that the data format for the remote Request page be:? (json_data)//For example://? ([{"_name": "Hunan Province", "_regionid": 134},{"_name": "Beijing", "_regionid": 143}]) 

Note that in getregion.aspx, when outputting JSON data, be sure to use request.querystring["Jsoncallback" to put what gets in front of the returned JSON data, assuming the actual fetch value is 42342348, Then the return value is 42342348 ([{"_name": "Hunan Province", "_regionid": 134},{"_name": "Beijing", "_regionid": 143}])

Because Getjson is the principle of the cross domain? Randomly changing a method name, and then returning the execution to achieve the goal of cross-domain response.

The following is a real example of cross-domain execution:

<script src= "Http://" type= "Text/javascript" ></script> 
< Script type= "Text/javascript" > 
//Cross-domain (can span all domain names) 
$.getjson ("Http://"). Jsoncallback=? ", {id:0, action: ' Jobcategoryjson '}, function (JSON) {alert (json[0].pid); alert (json[0].items[0]._name ); }); 
<script src= "Http://" type= "Text/javascript" ></script> 
< Script type= "Text/javascript" > 
//Cross-domain (can span all domain names) 
$.getjson ("Http://"). Jsoncallback=? ", {id:0, action: ' Jobcategoryjson '}, function (JSON) {alert (json[0].pid); alert (json[0].items[0]._name ); }); 

jquery cross-Domain principle:

The browser makes a homology check, which causes cross-domain problems, but there is an exception to this cross-domain check: HTML <Script> tags; we often use the SRC attribute of <Script>, Script static resources are placed under separate domain names or from other sites here is a URL; The URL can respond with a variety of results, such as JSON, and the returned JSON value becomes a <Script> The SRC attribute value of the label. This property value change does not cause the page to be affected. By convention, the browser provides a parameter in the URL's query string that returns to the browser as the prefix of the result;

Look at the following example:

<script type= "Text/javascript" src= "Http://" > </script> 
Response Value: Parseresponse ({"Name": "Cheeso", "Rank": 7}) 
<script type= "Text/javascript" src= Getjson?jsonp=parseresponse > </script> 
Response Value: Parseresponse ({"Name": "Cheeso", "Rank": 7}) 

This approach is called JSONP (click here if the link is invalid: JSONP), that is, the prefix referred to in JSON with padding is called "padding". So how does jquery come into being?

There seems to be no <Script> sign!? OKay, look at the source view:

The page is called Getjson:

Getjson:function (URL, data, callback) {return
 jquery.get (URL, data, callback, "JSON");

Continue to follow up

 Get:function (URL, data, callback, type) {
 //shift arguments if data argument was omited
 if (jquery.isfunction (data)) {
  type = type | | callback;
  callback = data;
  data = null;
 Return Jquery.ajax ({
  type: ' Get ',

Follow the Jquery.ajax, following is a snippet of the Ajax method:

 Build temporary JSONP function if (S.datatype = = "JSON" && ( && jsre.test ( | | jsre.te St (S.url))) {Jsonp = S.jsonpcallback | |
 ("Jsonp" + jsc++); Replace the =? 
 Sequence both in the query string and the data if ( { = ( + ""). Replace (jsre, "=" + Jsonp + "$");
 } S.url = S.url.replace (jsre, "=" + Jsonp + "$");
 We need to make sure//which a JSONP style response is executed properly = "script"; Handle Jsonp-style loading window[JSONP] = window[JSONP] | |
 Function (tmp) {data = tmp;
 Success ();
 Complete ();
 Garbage collect window[Jsonp] = undefined;
 try {delete window[Jsonp];
 catch (e) {} if (head) {head.removechild (script);
 } if (S.datatype = = "Script" && S.cache = = null) {S.cache = false;
 } if (S.cache = = False && type = = "Get") {var ts = now (); Try replacing _= if it is there var ret = S.url.replace (RTS, "$_= "+ ts +" $ "); If nothing is replaced, add timestamp to the end s.url = ret + (ret = = S.url)? (Rquery.test (S.url)? "&": "?"
 + "_=" + ts: ""); //If data is available, append data to URL for Get requests If ( && type = = "Get") {S.url = = (Rqu Ery.test (S.url)? "&": "?"
 +;  //Watch for a new set of requests if ( &&! {JQuery.event.trigger ("Ajaxstart"
 ); }//matches an absolute URL, and saves the domain var parts = rurl.exec (s.url), remote = Parts && (parts[1 ] && parts[1]!== Location.protocol | |
 PARTS[2]!==; If we ' re requesting a remote document//and trying to load JSON or script with a get if (S.datatype = = "Script" &A mp;& type = = ' get ' && remote ' {var head = document.getElementsByTagName (' head ') [0] | | | document.documentele
 var script = document.createelement ("script");
 SCRIPT.SRC = S.url; if (s.scriptcharset) {script.charset = S.scriptcharset;
 }//Handle Script loading if (!JSONP) {var done = false; Attach handlers for all browsers script.onload = Script.onreadystatechange = function () {if (!done && (!th
  Is.readystate | | This.readystate = = "Loaded" | |
  This.readystate = = "complete") {done = true;
  Success ();
  Complete ();
  Handle memory leak in IE script.onload = Script.onreadystatechange = null;
  if (head && script.parentnode) {head.removechild (script);
 }//Use InsertBefore instead of appendchild to circumvent a IE6 bug.
 This arises as a base node is used (#2709 and #4378).
 Head.insertbefore (script, head.firstchild);
 We handle everything using the SCRIPT element injection return undefined;


The above code lines 1th through line 10th: judgment is a JSON type call, a temporary Jsonp method is created for this call, and a random number is added, which is derived from the date value;

Focus on the 14th line, this line is very critical, doomed our results will ultimately be <Script> then construct the Script fragment, the 95th line in the head to add the fragment, to build the fruit;

Not only jquery, many JS frameworks are using the same Cross-domain solution, which is the principle of getjson across domains.

For more highlights, please click on the "Ajax cross-Domain technology summary" for in-depth study and research.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

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: 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.