Solution to js cross domain access problem

2011/08/30 16:08
Reading amount 1.9K

What caused ajax Can't cross domain request?

ajax It is actually through XMLHttpRequest Object to interact with data. For security reasons, the browser does not allow js The code performs cross domain operations, so a warning will be given.

Is there any perfect solution?

There are many solutions, but they can only be selected according to their own actual situation.

Cross domain security restrictions refer to the browser side. There are no cross domain security restrictions on the server side. So for this two Derived from two Class cross domain solutions, one is Server side operation Transfer similar agent mode , one is js Handle real cross domain access on the browser side.


The specific conditions are :

  1.   Mutual access between this domain and subdomains : www.aa.com and book.aa.com use document.domain = "aa.com";
  2. Mutual access between this domain and other domains : www.aa.com and www.bb.com use XMLHttpRequest Access proxy, i.e. server proxy mode
  3. Mutual access between this domain and other domains : www.aa.com and www.bb.com use JS Create dynamic script, < script> Tagged src Property for cross domain access

resolvent:

  1. If you want to achieve data interaction www.aa.com and book.aa.com It must be developed by you. You can set book.aa.com use iframe Add to www.aa.com Under a page of , stay www.aa.com and iframe Add it inside document.domain = "aa.com" In this way, the domain can be unified and cross domain access can be realized. Mosaic in the same domain as usual iframe Similarly, directly call the JS That's all right.
  2. This kind of situation is most frequently encountered and used. namely www.aa.com and www.bb.com You can only modify one, that is, the other is someone else's, and they tell you what the connection parameters are when you want to obtain data, and what the format of the returned data is. What you need to do is to make your server Act as a transit agent , let the server go to someone else's website to get data, and then return it to the browser.

There are many proxy transfer modes during server charging that can be implemented by server programs or modified server configurations, as shown below Apache Rewrite( mod_rewrite proxy Mode):
stay Apache Under the installation directory of conf/httpd.conf Add the following statement to the file:

LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so
LoadModule rewrite_module modules/mod_rewrite.so
RewriteEngine On
RewriteRule ^/_proxy/(.*)$ http:// $1 [P,L]


In this way, you can url Mapped to this server's /_proxy/ Below the directory , For example, you can visit Baidu like this http://html.duqn.com/_proxy/www.baidu.com


  The difference is that the request uses <script> Tag. This requirement also requires that you develop both domains. The principle is JS File injection, in this domain aa.com Generate a JS Label, its SRC Point to another requested domain bb.com A page of b b Just return the data, you can directly return JS Code of. because script Of src Properties can span domains. The code is simple

aa.com/a.jsp

<script type= "text/javascript" >
function myTest(data) {
     alert(data);
}
</script>
<script type= "text/javascript" src= " http://www.bb.com/index ! getData.action?jsoncallback=myTest" ></script>

bb.com/b.jsp The page code is as follows:

$(param.jsoncallback)({ "name" : "Zhang Huihua" , "QQ" : "350863780" })

b.jsp Page Pass $(param.jsoncallback) Get what the browser will call back later js function name:myTest

Actually, the client receives response As follows: myTest({"name": "Zhang Huihua", "QQ": "350863780"})

jQuery Cross domain access on browser side

at present jQuery $.ajax() support get Cross domain approach, which actually adopts jsonp To complete. The principle is the third method above, < script> Tagged src Property for cross domain access

Real case The code is as follows :

$.ajax({
     url: http: //Cross domain dns/index! searchJSONResult.action,
     type: "GET" ,
     dataType: 'jsonp' ,
     data: {name:”ZhangHuihua”},
     timeout: 5000,
     success: function (json) { //The client jquery defines the callback function in advance. After successfully obtaining the json data on the cross domain server, the callback function will be executed dynamically
         alert(json);
     },
     error: function (xhr, ajaxOptions, thrownError){
           alert( "Http status: " + xhr.status + " " + xhr.statusText + "\najaxOptions: " + ajaxOptions + "\nthrownError:" +thrownError + "\n" +xhr.responseText);
     }
 
});

be careful :

$.getJSON( " http:// Cross domain dns/index! searchJSONResult.action?name1=" +value1+ "&jsoncallback=?" , function (json){
     //Execution code
});

This method is actually the example above $.ajax({..}) api An advanced package of , Some $.ajax api The underlying parameters are encapsulated and invisible .

such ,jquery Will be assembled as follows url get request

http:// Cross domain dns/index!searchJSONResult.action?&jsoncallback=jsonp1236827957501&_=1236828192549&name=ZhangHuihua

At the response end (http:// Cross domain dns/index!searchJSONResult.action),

adopt jsoncallback = request.getParameter("jsoncallback") obtain jquery End to be recalled later js function name:jsonp1236827957501

then response The content of is a Script Tags:"jsonp1236827957501("+ Generated by request parameters json array +")";

jquery This will be dynamically loaded and called through the callback method js tag:jsonp1236827957501(json array );

This achieves the purpose of cross domain data exchange .


jsonp The basic principle of : Add one dynamically <script> Label, and script Tagged src There are no cross domain restrictions on properties. In this way , This cross domain approach is actually ajax XmlHttpRequest The agreement is irrelevant .

In fact "jQuery AJAX Cross domain issues " It's a false proposition ,jquery $.ajax The method name is misleading .

If set to dataType: 'jsonp', this $.ajax The method is the same as ajax XmlHttpRequest It doesn't matter , Instead JSONP agreement .

JSONP It is an unofficial protocol that allows integration on the server side Script tags Return to the client via javascript callback Cross domain access in the form of

JSONP I.e JSON with Padding Due to the limitation of the same origin policy, XmlHttpRequest Only resources of the current source (domain name, protocol, port) can be requested. If you want to make cross domain requests,

We can use html Of script Mark to make cross domain requests, and return the script Code, where you can directly use JSON transmit javascript Object.

This cross domain communication method is called JSONP

jsonCallback function jsonp1236827957501(....): It is registered by the browser client to obtain the json Data, callback function


Jsonp Principle:

First register a callback ( as :'jsoncallback'), Then put callback Name of ( as :jsonp1236827957501) Pass it to the server.

At this time, Mr. Server json Data.

Then use javascript Grammar, generating a function , function The name is the parameter passed 'jsoncallback' Value of jsonp1236827957501 .

Finally json The data is directly placed into the function In this way, a section is generated js The syntax document is returned to the client.

Client browser, parsing script Tag and execute the returned javascript Document, at this time javascript Document Data , As a parameter,

Passed in to the predefined client callback function ( In the above example jquery $.ajax() Method encapsulated success: function (json)) in . (Execute callback function dynamically)

so to speak jsonp In principle and <script src="http:// Cross domain /... xx.js"></script> Is consistent (qq Space uses this method to realize cross domain data exchange ) . JSONP It is a script injection (Script Injection) behavior , Therefore, there are certain potential safety hazards .


be careful ,jquey Yes, not supported post Mode cross domain .

Although using post + Dynamic generation iframe Is achievable post Cross domain purpose , But this is an extreme way , Not recommended .

It can also be said that get The cross domain mode is legal ,post In terms of safety , Is considered illegal , As a last resort, don't take the edge of the sword ..

The need for cross domain access on the browser side also seems to cause w3c 's attention , According to the data html5 WebSocket The standard supports cross domain data exchange , It should also be an optional solution for cross domain data exchange in the future .

Expand to read the full text
Loading
Click to join the discussion 🔥 (2) Post and join the discussion 🔥
Reward
two comment
nine Collection
zero fabulous
 Back to top
Top