Implementing JSONP Cross-domain with jquery

Source: Internet
Author: User
Tags domain server

Cross-domain security restrictions are referred to as browser-side, and server-side is non-existent cross-domain security restrictions.

So through the local server side through a similar httpclient way to complete the "cross-domain Access" work, and then in the browser side with Ajax to get the local server-side "cross-domain Access" the corresponding URL, to indirectly complete cross-domain access is also possible, but it is clear that the development of a larger, but the limit is very small, Many widgets open platform server side (such as the Sohu Blog open platform) in fact, this is not the scope of this discussion.

To discuss the browser side of the real cross-domain access, it is recommended that the current jquer$.ajax () support get mode of cross-domain, which is in fact the use of Jsonp way to complete.

Real Case:

var qsdate={

' Serchword ': $ ("#searchWord"). attr ("value"). ' Currentuserld ': $ ("#currentUesrld"). attr ("value"). ' Conditionbean.pagesize ': $ ("#pageSize"). attr ("value")

};

$.ajax ({

Async:false,

url:http://cross-Domain dns/document!searchjsonresult.action,

Type: "GET",

DataType: ' Jsonp ',

Jsomp: ' Jsoncallback ',

Data:qsdata,

timeout:5000,

Beforesend:function () {

Jsonp mode This method is not triggered, possibly because datatype is not an AJAX event if specified as Jsonp

},

Success:function (JSON) {//client jquery pre-defined callback function, after successfully acquiring JSON data on a cross-domain server, this callback function is executed dynamically

if (json.actionerrors.length!=0) {

alert (json.actionerrors);

}

Gendynamiccontent (Qsdata,type,json);

},

Complete:function (xmlhttprequest,textstatus) {

$.unblockul ({fadeout:10});

},

Error:function (XHR) {

Jsonp mode 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 ("Request error (Please check related network condition)");

}

});

Note: $.getjson ("//cross-domain dns/document!searchjsonresult.action?

name1= "+value1+" &jsoncallback=? ",

function (JSON) {

if (JSON. property name = = value) {

Execute code

}

});

This is actually the above $.ajax ({...}) An advanced package of APIs, some $.ajax API low-level parameters are encapsulated and not visible, so 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&currentuserld= 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 back to the client to achieve cross-domain access via JavaScript callback
JSONP is the 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 you want to make cross-domain requests,
We can make cross-domain requests by using the HTML script tag and return the script code to execute in the response, where you can pass the JavaScript object 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

Jsonp principle:

First register a callback (for example: ' Jsoncallback ') on the client, and then pass callback's name (for example: jsonp1236827957501) to the server. Note: After the server gets the value of callback, 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 jsonp1236827957501 of the parameter ' Jsoncallback ' passed up.

Finally, the JSON data is placed directly into the function in the form of a parameter, so that a document of JS syntax is generated and returned to the client.

The client browser, parses the script tag, and executes the returned JavaScript document, at which time the JavaScript document data, as parameters,
Passed into the client's pre-defined callback function (as in the previous example, the jquery $.ajax () method encapsulates the Success:function (JSON)). (Dynamic execution callback function)

Can say Jsonp way principle and <script src= "//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 script injection (scripts injection) behavior, so there are some security implications.

Example code for the principle:

The client's JavaScript code 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, must have callback to make a callback, here parentheses, is to let it in the form of statements block parsing <!--? Phpecho $_get["callback"]. (". Json_encode ($_get)."); ";? -

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,

Implementing JSONP Cross-domain with jquery

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.