JS cross-domain knowledge collation

Source: Internet
Author: User

Before the word "cross-domain" occurs frequently, we have used it very often. If the img,src of a site points to an image address of the B site, there is no doubt that this normally appears normally (and regardless of the anti-theft chain technology); Similarly, you can point the SRC attribute of the script tag to the scripting resources of other Web sites (and in some cases even encourage this, To take advantage of the load advantages of other websites and reduce the concurrency of their own servers. However, if you use JS to proactively request data from other websites, such as Ajax, you will encounter a frustrating cross-domain problem, which is what we call cross-domain. For security reasons, cross-domain access is forbidden by the large browsers. This involves the concept of the same-origin policy: the same-origin policy prevents scripts loaded from one domain from getting or manipulating document properties on another domain. That is, the domain of the requested URL must be the same as the domain of the current Web page. This means that the browser isolates content from different sources to prevent operations between them.

The specific security issues brought by cross-domain bloggers did not delve into the matter, we can fill their brains.

However, in many cases, especially as the Internet continues to evolve today, we need to request front-end interfaces from different partners or data providers, before the way to cross-domain access is not normalized (client-side cross-domain access requirements seem to have attracted the attention of the network, see the data said HTML5 The WebSocket standard supports cross-domain data exchange and should also be a solution for future optional cross-domain data exchange, what can be done to circumvent its limitations? There are many answers (though all are troublesome), the most commonly used is the so-called Jsonp cross-domain.

JSONP principle

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 .

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 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. This cross-domain communication method is called JSONP.

Here's a simple example:

1 <!DOCTYPE HTML Public "-//W3C//DTD XHTML 1.0 transitional//en" "http://www.w3.org/TR/xhtml1/DTD/ Xhtml1-transitional.dtd ">  2 <HTMLxmlns= "http://www.w3.org/1999/xhtml" >  3 <Head>  4     <title>Test Jsonp</title>  5     <Scripttype= "Text/javascript">  6             functionjsonpcallback (Result)7             {  8 alert (result.msg); 9             }  Ten         </Script>   One     <Scripttype= "Text/javascript"src= "Http://crossdomain.com/jsonServerResponse?jsonp=jsonpCallback"></Script>   A </Head>   - <Body>   - </Body>   the </HTML>   

Briefly describe the principle and process: first register a callback with the client, and then pass the callback name to the server (where the client and the server contract are passed with the value of key JSONP query string). At this point, the server becomes JSON data. Then, in JavaScript syntax, a function is generated, and the function name is the parameter Jsonp 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, which executes the predefined callback function.

From the above summary can be introduced: In addition to return function in the form of JS code fragment, the server can naturally return all conforming executable JS fragments.

The disadvantage of JSONP is that it only supports get requests and does not support other types of HTTP requests such as Post, which only supports cross-domain HTTP requests, and does not solve the problem of how to make JavaScript calls between two pages in different domains. (also below)

The Jsonp of jquery

As mentioned earlier, JSONP is not an AJAX request, but jquery still provides cross-domain requests in a manner consistent with Jquery.ajax:

$.ajax ({    URL: ' http://crossdomain.com/jsonServerResponse '    , '    GET ', ' Jsonp ',     "Callback",    ' functionname ',    function  (data, Textstatus, JQXHR) {}    //...});

As shown above, datatype is set to JSONP to indicate that this is a cross-domain request, JSONP is set as the query string key for the service-side scheduled transfer function name, and jsonpcallback is the JS function name; If Jsonpcallback is not set, Then jquery will automatically generate a random function name (load a global function in the Window object, and when the code is inserted, the function executes and is removed after execution), infer that the automatically generated function will callback the success function in the code above. ( When you manually assign a value to Jsonpcallback, do not know whether the success function will be callback, or jquery will look for predefined functions, if not found the error?) Bo Master lazy, try it again later. Of course jquery provides us with a simple version, $.getjson, which is not to be discussed here.

Note that the JQXHR parameter in the Success function, which is an authentic Jqxhr object in an AJAX request, can also be seen as a XMLHttpRequest object (inherited or encapsulated), but not in the JSONP request. Can hardly bring us the information that is most useful in XMLHttpRequest: it lacks XMLHttpRequest request state information, so it does not trigger most of the callback functions, such as error, Complete and so on (jQuery1.9.0), and the success function that can be recalled should be triggered by the load event labeled by the script, which is quite different from the mechanism of Ajax relying on XMLHttpRequest state. After testing, Zepto from jquery (v1.1.3), the error function executes when the JSONP request errors, such as when the header returns a 401 error when loading the JS document, but the JQXHR parameter of the function is also not an authentic JQXHR type and cannot even get the header information of the response, in which case We are just told that something went wrong, but we don't know the exact error message. Similar to the response header hosting useful information scenarios, bloggers do not recommend the use of JSONP, it can be said that the use of Jsonp a premise is: In addition to network anomalies, such as non-business exceptions, all business anomalies (in summary, All exceptions thrown from the server receiving the request to the return response time will need to be returned directly to the client in the form of the request result, facilitating client callback analysis.

Resources:

Principle analysis of Jsonp cross-domain

Jquery.ajax ()

Reprint please specify the source of this article: http://www.cnblogs.com/newton/p/3930474.html

JS cross-domain knowledge collation

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.