Easily resolve Cross-domain access problems with jquery and Jsonp _jquery

Source: Internet
Author: User
Tags error handling script tag domain server

Time passed quickly, and was pulled back to JS battlefield, cross-domain problem this scar again open pain.

Fortunately, with jquery to help, the cross-domain problem seems to be less difficult. This time also take this opportunity to the cross domain question to the inquisitive, the actual development project, has consulted the related data, is solves the cross-domain problem. It is necessary to write down the memo.

Cross-domain security restrictions refer to the browser side. There is no Cross-domain security limit on the server side, so the work of "Cross-domain access" is done through the native server side in a similar httpclient manner, and then the native server side "Cross-domain access" is obtained with Ajax on the browser end The corresponding URL. It is also possible to perform cross-domain access indirectly. But it is clear that the development is relatively large, but the limit is minimal, many widgets open platform server (such as the Sohu Blog open platform) actually do. Not in the scope of this discussion.

To discuss true Cross-domain access on the browser side, it is recommended that the current jquery $.ajax () support get mode Cross-domain, which is actually done in a JSONP way.

Real Case:

Copy Code code as follows:

var qsdata = {' Searchword ': $ ("#searchWord"). attr ("value"), ' Currentuserid ': $ ("#currentUserId"). attr ("value"), ' Conditionbean.pagesize ': $ ("#pageSize"). attr ("value")};

$.ajax ({
Async:false,
url:http://cross-Domain dns/document!searchjsonresult.action,
Type: "Get",
DataType: ' Jsonp ',
JSONP: ' Jsoncallback ',
Data:qsdata,
timeout:5000,
Beforesend:function () {
Jsonp This method is not triggered. The reason may be that datatype, if specified as JSONP, is no longer an AJAX event.
},
Success:function (JSON) {//client jquery predefined callback function that dynamically performs this callback function after successfully acquiring JSON data on a cross-domain server
if (json.actionerrors.length!=0) {
alert (json.actionerrors);
}
Gendynamiccontent (Qsdata,type,json);
},
Complete:function (XMLHttpRequest, Textstatus) {
$.unblockui ({fadeout:10});
},
Error:function (XHR) {
Jsonp This method is not triggered. The reason may be that datatype, if specified as JSONP, is no longer an AJAX event.
Request Error Handling
Alert (Please check the correlation network condition for errors);
}
});


Note:
Copy Code code as follows:

$.getjson ("http://cross-domain dns/document!searchjsonresult.action?name1=" +value1+ "&jsoncallback=?",
function (JSON) {
if (JSON. property name = = value) {
Executing code
}
});

This is actually an advanced encapsulation of the previous example $.ajax ({.}) API, and some $.ajax API low-level parameters are encapsulated and invisible.
This way, jquery is assembled into the following URL get request
http://cross-domain dns/document!searchjsonresult.action?&jsoncallback=jsonp1236827957501&_=1236828192549& Searchword=%e7%94%a8%e4%be%8b&currentuserid=5351&conditionbean.pagesize=15

At the response end (http://cross-domain dns/document!searchjsonresult.action),
Using Jsoncallback = Request.getparameter ("Jsoncallback") to get the JS function that the jquery side will then callback name:jsonp1236827957501
Then response's content is a script Tags: "jsonp1236827957501 (" + JSON array generated by request parameters + ");
jquery dynamically loads the call to this JS tag:jsonp1236827957501 (JSON array) via the callback method;
This achieves the goal of cross domain data exchange.

The basic principle of JSONP is to dynamically add a <script> tag, and the SRC attribute of the script tag is not cross-domain. In this way, this cross-domain approach has nothing to do with the Ajax XMLHttpRequest protocol.
In fact, "jquery Ajax Cross-domain Problem" has become a pseudo proposition, jquery $.ajax method name is misleading.

If set to datatype: ' Jsonp ', this $.ajax method has nothing to do with the Ajax XMLHttpRequest, but instead the JSONP protocol.

JSONP is an unofficial protocol that allows the server-side integration script tags to return to the client, implementing Cross-domain access via JavaScript callback JSONP that is, JSON with Padding. Due to the restriction of the homology policy, XMLHttpRequest only allows resources to be requested for the current source (domain name, protocol, port). If Cross-domain requests are to be made, we can make cross-domain requests by using the HTML script tag and return the script code to execute in the response, where the JavaScript object can be passed directly using JSON. This cross-domain mode of communication is called JSONP.

Jsoncallback function jsonp1236827957501 (...): is the browser client registers, gets the JSON data on the cross domain server, the callback function

Jsonp principle:

First register a callback (such as ' Jsoncallback ') on the client and pass the callback name (such as: jsonp1236827957501) to the server. Note: When the server gets the callback value, it needs to use jsonp1236827957501 (...) Include the JSON content that will be output, at which point the server generates JSON data to be properly received by the client.

Then, in JavaScript syntax, a function is generated, and the function name is the value of the parameter ' Jsoncallback ' passed up jsonp1236827957501.

Finally, the JSON data is placed into function directly in the form of a parameter, which generates a document of JS syntax and returns it to the client.

The client browser, parsing the script tag, and executing the returned JavaScript document, at which point the JavaScript document data, as parameters,
Passed into the client's predefined callback function (as in the Success:function (JSON) encapsulated by the jquery $.ajax () method in the example above). (Dynamic execution of callback functions)

It can be said that the principle of Jsonp and <script src= "http://cross-domain/...xx.js" ></script> is consistent (QQ space is a large number of this way to achieve cross-domain data exchange). JSONP is a scripting Injection (script injection) behavior, so there are some security risks.

Example code for the principle:

Copy Code code as follows:

JavaScript code for the client
var script=document.createelement ("script");
Script.src= "http://www.pl4cj.com:8888/5/6/action.php?param=123&callback=" +fnname;
document.getElementsByTagName ("Head") [0].appendchild (script)

Server-side PHP code, there must be a callback to the callback, here with parentheses, is to let it in the form of a statement block to parse
<?php
<span style= "COLOR: #ff00ff" >echo $_get["callback"]. " (". Json_encode ($_get)."); ";
</span>?

Note that Jquey is not supported for post-domain cross-domain.

Why, then?
Although the use of post + dynamic generation of IFRAME can achieve the purpose of the post Cross-domain, but this is a more extreme way, not recommended.
It can also be said that the cross domain of Get way is legal, post way from the security point of view, is considered illegal, last but not sword walk slant.

The need for client-side Cross-domain access seems to have also attracted the attention of the Global consortium, looking at the data. HTML5 WebSocket standard supports Cross-domain data exchange and should also be a future alternative to Cross-domain data interchange solutions

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.