Cross-origin ajax access to JQuery

Source: Internet
Author: User

The cross-origin issue has always been a tangled issue. Next I will summarize the principles and Solutions of ajax cross-origin access and JQuery cross-origin. I hope this method will help you.

Cross-origin of JSThe problem is that many programmers still think that JS cannot be cross-origin. In fact, this is a wrong idea;

There are many people looking for solutions on the Internet, and there are a lot of articles on how to use IFRAME to solve the problem. Is it so complicated?

In fact, it is very simple. If you use JQUERY, a getjson method will be done, and a line of code will be done.

Today, on April 9, August 2, 2013, I took another time to sort out and modify the online call optimization method.

I have provided the online test call function for your convenience. Click to view

In fact, there are two ways to achieve cross-origin: one is to access through js cross-origin; the other is to write code in the background for access.

The following describes the implementation of the two methods:

Idea 1: Cross-origin access through js

1. The server side (Remote Access segment) constructs the specified json format:

The Code is as follows: Copy code
Var url = "http://www.bKjia. c0m/CsAjax. do? Method = getCrossJson & jsoncallback =? "
$. GetJSON (url,
{Www_url: "www. bKjia. c0m "},
Function (json ){
// Return format :? (Json_data)
/* Returned data :? ([{"Www_url": "www. bKjia. c0m", "www_name": "www_name ",
"Items": [{"p_name": "Anhui Province", "p_index": 340000 },{ "p_name": "Beijing", "p_index": 110000}]) */
// Call the instance: alert (json [0]. www_url );
});
 


Note: CsAjax. do? In method = getCrossJson, when outputting JSON data, you must include the jsoncallback parameter and put the obtained content before the returned JSON data. Assume that the actually obtained value is Jquery123456_7890123, the returned value is Jquery123456_7890123 ([{"www_url": "www. bKjia. c0m "," www_name ":" www_name "," items ": [{" p_name ":" Anhui Province "," p_index ": 340000 },{" p_name ": "Beijing", "p_index": 110000}]);

This post posts my remote client to obtain code. Other languages written in java are similar:

The Code is as follows: Copy code
String www_url = (String) request. getAttribute ("www_url ");
String jsoncallback = (String) request. getAttribute ("jsoncallback ");
If (StringUtils. isBlank (www_url )){
Www_url = "www. bKjia. c0m ";
}
JSONObject jsonb = new JSONObject ();
 
Jsonb. put ("www_url", www_url );
Jsonb. put ("www_name", "aison Homestead ");
 
JSONArray items = new JSONArray ();
JSONObject item = new JSONObject ();
Item. put ("p_name", "Anhui Province ");
Item. put ("p_index", 340000 );
Items. put (item );
Jsonb. put ("p_name", "Beijing ");
Jsonb. put ("p_index", 110000 );
Items. put (item );
Jsonb. put ("items", items );
 
String json = jsoncallback + "([" + jsonb. toString () + "])";
If (StringUtils. isNotBlank (jsoncallback )){
// Return the specially constructed data: json to the page
} Else {
// Return normal data jsonb to the page
}

Because the cross-origin principle of getJSON is? Randomly change the method name and return the executed method to achieve cross-origin response.

Ii. Actual client calls. The following is a real example of cross-domain execution (cross-domain name across all domains ):

The Code is as follows: Copy code

<Script src = "/scripts/jquery. js" type = "text/javascript"> </script>
<Script type = "text/javascript">
$. GetJSON ("http://www.bKjia. c0m/CsAjax. do? Method = getCrossJson & jsoncallback =? ",
{Www_url: "www. bKjia. c0m "},
Function (json ){
Alert (json [0]. www_url );
Alert (json [0]. www_name );
Alert (json [0]. items [0]. p_name );
});
</Script>

Access by writing code in the background


There is a flaw in the first approach: if you cannot control the server to be accessed, you will not be able to implement it. Therefore, the second approach is provided for direct access through HttpClient and HttpGet in the background,

Then obtain the accessed data in the background. After processing, return to the page.

For more information, see my article.


JQuery cross-origin principle


The browser performs the same-origin check, which causes cross-origin problems. However, this cross-origin check also has an exception that is the HTML <Script> flag. We often use the src attribute of <Script>, when static script resources are placed under an independent domain name or from other sites, this is a url. There are many types of url response results, such as JSON, the returned Json value is the src attribute value of the <Script> tag. this change in attribute values does not affect the page. by convention, the browser provides a parameter in the URL query string, which will be returned to the browser together as the result prefix;

See the following example:

The Code is as follows: Copy code
<Script type = "text/javascript" src = "http://domain2.com/getjson? Jsonp = parseResponse "> </script>

Response value: parseResponse ({"Name": "Cheeso", "Rank": 7 })

This method is called JsonP; (if the link has expired, click here: JSONP); that is, the prefix mentioned above in JSON with padding is called "padding ". How is jQuery implemented?

It seems that there is no <Script> MARK !? OKay,


The page calls getJSON:

The Code is as follows: Copy code
GetJSON: function (url, data, callback ){
Return jQuery. get (url, data, callback, "json ");
},

 
Continue to follow up

The Code is as follows: Copy code
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 ",
Url: url,
Data: data,
Success: callback,
DataType: type
});


Follow up with jQuery. ajax. The following is the code snippet of the ajax method:

The Code is as follows: Copy code
// Build temporary JSONP function
If (s. dataType = "json" & (s. data & jsre. test (s. data) | jsre. test (s. url ))){
Jsonp = s. jsonpCallback | ("jsonp" + jsc ++ );

// Replace the =? Sequence both in the query string and the data
If (s. data ){
S. data = (s. data + ""). replace (jsre, "=" + jsonp + "$1 ");
}

S. url = s. url. replace (jsre, "=" + jsonp + "$1 ");

// We need to make sure
// That a JSONP style response is executed properly
S. dataType = "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, "$1 _ =" + ts + "$2 ");

// If nothing was 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 (s. data & type = "GET "){
S. url + = (rquery. test (s. url )? "&":"? ") + S. data;
}

// Watch for a new set of requests
If (s. global &&! JQuery. active ++ ){
JQuery. event. trigger ("ajaxStart ");
}

// Matches an absolute URL, and saves the domain
Var parts = rurl.exe c (s. url ),
Remote = parts & (parts [1] & parts [1]! = Location. protocol | parts [2]! = Location. host );

// If we're requesting a remote document
// And trying to load JSON or Script with a GET
If (s. dataType = "script" & type = "GET" & remote ){
Var head = document. getElementsByTagName ("head") [0] | document.doc umentElement;
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 &&(! This. 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 an IE6 bug.
// This arises when a base node is used (#2709 and #4378 ).
Head. insertBefore (script, head. firstChild );

// We handle everything using the script element injection
Return undefined;
}

The preceding Code contains lines 1st to 10th: determine that the JsonP method is a JSON call, create a temporary JsonP method for this call, and add a random number, which is derived from the date value;

This is what Taven. Li Xiyuan calls "randomly changing the method name ";

Focus on the second row. This row is critical and our final result is <Script>. Then we construct the Script segment, and add the segment to the Head of the second row to complete the final result;

Not only jQuery, but many js frameworks use the same cross-origin scheme. :) speaking of this, well, this is the cross-origin principle of getJSON. Zhao Benshan said, "this is the case"

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