Use jQuery and JSONP to easily solve cross-origin access problems.

Source: Internet
Author: User

Use jQuery and JSONP to easily solve cross-origin access problems [] And jqueryjsonp cross-Origin

Address: http://www.jb51.net/article/46463.htm

Fortunately, with the help of jquery, cross-domain problems seem less difficult. this time, I also took this opportunity to give a thorough understanding of cross-origin issues. Based on the actual development project, I checked the relevant information and solved the cross-origin issue .. it is necessary to write down the memo.

Cross-origin security restrictions refer to the browser. the server does not have cross-origin security restrictions. Therefore, the local server completes "cross-origin access" in a way similar to httpclient, then, use AJAX on the browser side to obtain the url corresponding to "cross-origin access" on the local server side. to indirectly complete cross-origin access. however, it is clear that the development volume is large, but the restrictions are also the least. Many widgets Open Platform servers (such as sohu blog Open Platform) are actually implemented. not in the scope of this discussion.

We will discuss the real cross-origin access on the browser side. We recommend that jQuery $. ajax () currently supports cross-origin access through get, which is actually completed using jsonp.

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 dataType: 'jsonp', 9 jsonp: 'jsoncallback', 10 data: qsData, 11 timeout: 5000,12 beforeSend: function () {13 // jsonp mode this method is not triggered. the reason may be that if dataType is specified as jsonp, it is no longer an ajax event 14}, 15 success: function (json) {// The client jquery pre-defined callback function, after obtaining the json data on the Cross-origin server, the callback function 16 if (json. actionErrors. length! = 0) {17 alert (json. actionErrors); 18} 19 genDynamicContent (qsData, type, json); 20}, 21 complete: function (XMLHttpRequest, textStatus) {22 $. unblockUI ({fadeOut: 10}); 23}, 24 error: function (xhr) {25 // jsonp this method is not triggered. the cause may be that if dataType is specified as jsonp, it is no longer an ajax event. 26 // request error handling 27 alert ("request error (please check the relevant network status .) "); 28} 29 });


Note:
The Code is as follows:

1 $. getJSON ("http: // cross-domain dns/document! SearchJSONResult. action? Name1 = "+ value1 +" & jsoncallback =? ", 2 function (json) {3 if (json. attribute name = value) {4 // Execution Code 5} 6 });

 


This method is actually an advanced encapsulation of the $. ajax ({...}) api in the previous example. Some underlying parameters of $. ajax APIs are encapsulated and invisible.
In this way, jquery is assembled into the following url get request
Http: // cross-domain dns/document! SearchJSONResult. action? & Jsoncallback = jsonp1231627957501 & _ = 1236828192549 & searchWord = % E7 % 94% A8 % E4 % BE % 8B login tUserId = 5351 & conditionBean. pageSize = 15

 

On the response side (http: // cross-domain dns/document! SearchJSONResult. action ),
Use jsoncallback = request. getParameter ("jsoncallback") to obtain the js function name: jsonp1231627957501 to be called back by jquery.
Then the response content is a Script Tags: "jsonp1231627957501 (" + json array generated by Request Parameters + ")";
Jquery dynamically loads and calls this js tag through the callback method: jsonp1231627957501 (json array );
This achieves the purpose of cross-Origin data exchange.

The most basic principle of jsonp is to dynamically Add a <script> tag, while the src attribute of the script tag has no cross-domain restrictions. In this case, this cross-origin method is not related to the ajax XmlHttpRequest protocol.
In this way, the "jQuery AJAX cross-origin issue" becomes a pseudo-proposition. The jquery $. ajax method name is misleading.

If it is set to dataType: 'jsonp', the $. ajax method has nothing to do with ajax XmlHttpRequest, and is replaced by the jsonp protocol.

JSONP is an unofficial protocol that allows the server to integrate Script tags to return to the client, and implement cross-origin access to JSONP (JSON with Padding) through javascript callback. Due to the same-origin policy restrictions, XmlHttpRequest only allows requests to resources of the Current Source (domain name, protocol, port. For cross-origin requests, we can use the html script tag to perform cross-origin requests, and return the script code to be executed in the response, where javascript objects can be directly transmitted using JSON. This cross-origin communication method is called JSONP.

JsonCallback function: jsonp1231627957501 (...): it is registered by the browser client. After obtaining the json data on the Cross-origin server, the callback function

Sample Code of the principle:

The Code is as follows:
// Client 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)

// The PHP code on the server must have callback for callback. brackets should be added to resolve the code in the statement block method.
1 <? Php
2 <SPAN> 3 </SPAN>? 


Note that jquey does not support cross-origin post.

 

Why?
Although the use of post + dynamic iframe generation can achieve the purpose of post cross-origin, this is an extreme method and is not recommended.
It can also be said that the cross-origin of the get method is legal, and the post method is considered illegal from the security point of view ..

The demand for cross-origin access on the client side also attracted w3c's attention. It is said that the html5 WebSocket standard supports cross-Origin data exchange and should also be an optional cross-Origin data exchange solution in the future.

I wanted to write these things by myself. I occasionally found this article better than I did, so I reproduced it ~~~~

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.