Easily solve cross-domain access problems with jquery and Jsonp "Go"

Source: Internet
Author: User
Tags domain server

Original address: http://www.jb51.net/article/46463.htm

Fortunately, with jquery, cross-domain issues seem to be less difficult. This time also take this opportunity to the cross-domain problem to the inquisitive, actual development projects, access to relevant information, is considered to solve the cross-domain problem. It is necessary to write down the memo.

Cross-domain security restrictions are referred to as browser-side. There is no cross-domain security restriction on the server side, so cross-domain access is done through a similar httpclient approach through the native server, and then the browser-side uses Ajax to get the native server-side "cross-domain Access" The corresponding URL. To indirectly complete cross-domain access is also possible. But it is clear that the amount of development is relatively large, but the limit is minimal, many widgets open platform server side (such as 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 jquery $.ajax () currently supports the cross-domain of Get methods, which is actually done in the JSONP way.

Real Case:

The code is as follows:
 1 var qsdata = {' Searchword ': $ ("#searchWord"). attr ("value"), ' Currentuserid ': $ ("#currentUserId"). attr ("value") , ' Conditionbean.pagesize ': $ ("#pageSize"). attr ("value")}; 2 3 4 $.ajax ({5 async:false, 6 url:http://cross-domain dns/document!searchjsonresult.action, 7 type: "GET", 8 Datat  ype: ' Jsonp ', 9 jsonp: ' Jsoncallback ', data:qsdata,11 timeout:5000,12 beforesend:function () {//JSONP This method is not triggered. The reason may be datatype if you specify JSONP, it's not an AJAX event.},15 Success:function (JSON) {//client jquery pre-defined callback function successfully acquires cross-        The callback function is dynamically executed after the JSON data on the domain server (json.actionerrors.length!=0) {alert (json.actionerrors); 18}19 Gendynamiccontent (Qsdata,type,json),},21 complete:function (XMLHttpRequest, textstatus) {$.unblockUI ({fadeout:10}); },24 error:function (XHR) {//jsonp Mode This method is not triggered. The reason may be datatype if you specify JSONP, it's not an AJAX event. 26//Request error handling AL ERT ("Request error (Please check the correlation network condition.)"); }29}); 


Attention:
The code is as follows:

1 $.getjson ("HTTP//cross-domain dns/document!searchjsonresult.action?name1=" +value1+ "&jsoncallback=?", 2       function (JSON) {3       if (json. property name = = value) {4       //Execute code 5             }6         });


This is actually a high-level package of the previous example $.ajax ({..}) API, and some of the $.ajax API's underlying parameters are encapsulated and not visible.
This way, jquery is assembled into the URL get request as follows
HTTP//cross-domain dns/document!searchjsonresult.action?&jsoncallback=jsonp1236827957501&_=1236828192549& Searchword=%e7%94%a8%e4%be%8b¤tuserid=5351&conditionbean.pagesize=15

On the response side (HTTP///cross-domain dns/document!searchjsonresult.action),
by Jsoncallback = Request.getparameter ("Jsoncallback"), we get the JS function of the jquery end to be recalled later name:jsonp1236827957501
Then the content of the response is a script Tags: "jsonp1236827957501 (" + by the request parameters generated by the JSON array + ")";
jquery will invoke this JS tag:jsonp1236827957501 (JSON array) dynamically via callback method.
This achieves the purpose of cross-domain data exchange.

The most basic principle of JSONP is: adding a <script> tag dynamically, and the SRC attribute of the script tag is not a cross-domain limitation. In this way, this cross-domain approach is actually unrelated to 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 Ajax XMLHttpRequest, instead it is the JSONP protocol.

JSONP is an unofficial protocol that allows the server-side integration of script tags to return to the client, using the form of JavaScript callback for cross-domain access JSONP that is JSON with Padding. Due to the limitations of the same-origin policy, XMLHttpRequest only allows resources to be requested for the current source (domain name, protocol, port). If cross-domain requests are 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 communication method is called JSONP.

Jsoncallback function jsonp1236827957501 (...): A callback function that is registered by the browser client and gets the JSON data on the cross-domain server

Example code for the principle:

The code is as follows:
Client-side JavaScript code
1 var script=document.createelement ("script");
2 script.src= "http://www.pl4cj.com:8888/5/6/action.php?param=123&callback=" +fnname; 3 document.getElementsByTagName ("Head") [0].appendchild (script)

Server-side PHP code, must have callback to make callbacks, and here parentheses, is to let it in the form of a block of statements to parse
1 <?php
2 <span style= "COLOR: #ff00ff" >echo $_get["callback"]. " (". Json_encode ($_get)."); "; 3 </span>?


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

Why is it?
Although the use of post + dynamic generation of IFRAME can achieve the purpose of post cross-domain, but this is a more extreme way, is not recommended.
can also say get way cross-domain is legal, post way from security point of view, is considered illegal, last but not the sword walk Pifo.

The need for client-side cross-domain access seems to have attracted the attention of the HTML5 WebSocket standard supports cross-domain data exchange and should also be a future-selectable cross-domain data exchange solution

Originally wanted to write these things, occasionally found this article, than I write good, so reproduced over, hehe ~ ~ ~ ~ ~ ~

Easily solve cross-domain access problems with jquery and Jsonp "Go"

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.