js Cross-domain problem, I think a lot of programmers mind inside also think 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, to teach them to solve with an iframe 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.
Today, August 2, 2013, another time to clean up the next, modified the method of optimizing the online call.
I am here to provide the online test call function to facilitate testing. Click to view
In fact, there are two ways to cross the domain, the idea of one: is through JS cross-domain access; idea two: is to write code access through the background
The following is the implementation of two methods:
Idea one: cross-domain access via JS
One, server-side (remote access segment), constructs the specified JSON format:
code is as follows |
copy code |
var url =" http://www.111cn.net /csajax.do?method=getcrossjson& Jsoncallback=? " $.getjson (URL, {www_url: "Www.111cn.net"}, function (JSON) { br> //return format:? (json_data) /* Return data:? ( [{"Www_url": "Www.111cn.net", "Www_name": "Www_name", "Items": [{"P_name": "Anhui Province", "P_index": 340000},{"P_name": "Beijing", "P_index": 110000}]}) */ //Invocation instance: Alert (json[0].www_url); }); |
Note: In Csajax.do?method=getcrossjson, when outputting JSON data, be sure to take parameters: Jsoncallback, and put what you get in front of the return JSON data, assuming that the actual value you get is jquery123456_ 7890123, the return value is jquery123456_7890123 ([{"Www_url": "Www.111cn.net", "Www_name": "Www_name", "items": [{"P_name": "Anhui Province "," P_index ": 340000},{" P_name ":" Beijing "," P_index ": 110000}]});
This is attached to my remote end to get code Java written in other languages like reference:
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.111cn.net"; } Jsonobject jsonb = new Jsonobject ();
Jsonb.put ("Www_url", Www_url); Jsonb.put ("Www_name", "SNF Home");
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)) { To return a specially constructed data: JSON to a page } else { Return the normal data jsonb to the page } |
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.
Second, the client actually calls, the following is a real example of cross-domain execution (can be across all domain names):
The code is as follows |
Copy Code |
<script src= "/scripts/jquery.js" type= "Text/javascript" ></script> <script type= "Text/javascript" > $.getjson ("http://www.111cn.net/CsAjax.do?method=getCrossJson&jsoncallback=?"), {www_url: "Www.111cn.net"}, function (JSON) { alert (Json[0].www_url); alert (json[0].www_name); alert (json[0].items[0].p_name); }); </script> |
Background Write code access
The first idea has a flaw: if you need access to the server you can not control, then you can do nothing, so provide a second idea, backstage through httpclient and HttpGet direct access,
Then in the background to get access to the data, in doing processing, returned to the page can be.
This can refer to my article: Youdao translation use
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 responds with a variety of results, such as JSON, and the returned JSON value becomes the SRC attribute value of the <Script> tag. This property value change does not cause the page to affect. By convention, the browser provides a parameter in the URL's query string, which returns the prefix to the browser as the result;
Look at 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 approach is called JsonP;(if the link has expired click here: JsonP): JSON with padding the prefix mentioned above is called "padding". So how does jQuery come into being?
There seems to be no <Script> sign!? OKay,
The page is called 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 the Jquery.ajax, following is a 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 + "$"); }
S.url = S.url.replace (jsre, "=" + Jsonp + "$");
We need to make sure That's 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 + "$");
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 the 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.exec (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.documentelement; 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 the 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;
This place is what Taven Li Xiyuan called "Random Change a method name";
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, a lot of JS frameworks are using the same Cross-domain solution,: "Here, well, this is the principle of Getjson cross-domain," Zhao Benshan said "the situation is such a situation."