Cross-origin Javascript knowledge

Source: Internet
Author: User
Tags call back

Cross-origin Javascript knowledge

Summary of JS cross-origin knowledge:

Before the term "cross-origin" often appeared, we used it frequently. For example, if the img and src of website A point to an image address of website B, there is no doubt that this is normally displayed (regardless of anti-leech technology). Similarly, you can direct the src attribute of the script tag to the script resources of other websites (in some cases, you may even encourage it to take full advantage of the load advantages of other websites and reduce the concurrency of your servers ). However, if you use js to actively request data from other websites, such as ajax, you will encounter depressing cross-origin problems, which is what we usually call cross-origin. For security reasons, cross-origin access is disabled by various browsers by default. This involves the concept of a same-origin policy: a same-origin policy prevents scripts loaded from one domain from obtaining or operating document properties in another domain. That is to say, the domain of the requested URL must be the same as that of the current Web page. This means that the browser isolates content from different sources to prevent operations between them.

The specific security problems brought about by cross-origin are not discussed in detail by bloggers.

However, in many cases, especially as the Internet continues to grow, we need to request frontend interfaces from different partners or data providers, before the cross-origin access method is standardized (the client's cross-origin access needs also attract w3c attention. See the reference that the html5 WebSocket standard supports cross-Origin data exchange, it should also be an optional cross-Origin data exchange solution in the future.) Is there any way to bypass its restrictions? There are many answers (though difficult). The most common answer is the so-called JSONP cross-origin.

JSONP Principle

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.

JSONP is JSON with Padding. Due to the same-origin policy restrictions, XmlHttpRequest only allows requests to resources of the Current Source (domain name, protocol, port. If you want to perform a cross-origin request, you can use the html script tag to perform a cross-origin request and return the script code to be executed in the response. This cross-origin communication method is called JSONP.

Here is a simple example:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 

  

Briefly describe the principle and process: first register a callback on the client, and then pass the callback name to the server (here the client and server agree to pass the query string value with the key as jsonp ). In this case, the server is converted into json data. Then, a function is generated in javascript syntax. The function name is the passed parameter jsonp. Finally, place the json data directly in the function as an input parameter. In this way, a js syntax document is generated and returned to the client. The client browser parses the script tag and executes the returned javascript document, that is, the predefined callback function is executed.

From the above description, we can introduce: In addition to js code snippets in the form of return functions, the server can naturally return all executable js snippets that conform to the specifications.

The disadvantage of JSONP is that it only supports GET requests but not POST and other types of HTTP requests. It only supports cross-origin HTTP requests, it cannot solve the problem of how to call JavaScript between two pages in different domains. (Below)

Jsonp of jQuery

As mentioned above, jsonp is not an ajax request, but jQuery still provides the same method as jQuery. ajax for cross-origin requests:

$.ajax({  url: 'http://crossdomain.com/jsonServerResponse',  type: 'GET',  dataType: 'jsonp',  jsonp: "callback",  jsonpCallback: 'functionName',  success: function (data, textStatus, jqXHR) { }  //……});

  

As shown above, if ype is set to jsonp, it indicates that this is a cross-origin request. jsonp is set to the query string key of the predefined function name passed by the server, and jsonpCallback is the js function name. If jsonpCallback is not set, then jQuery will automatically generate a random function name (loading a global function in the window object. When the code is inserted, the function will be executed and removed after execution ), it can be inferred that the automatically generated function calls back the success function in the above Code. (When manually assigning values to jsonpCallback, I don't know if the success function will call back or if jQuery will look for a predefined function. If no value is found, an error is returned? The blogger is lazy. Please try again later .) Of course, jQuery provides us with a simple version, $. getJSON, which will not be described here.

Note that the jqXHR parameter in the success function is an authentic jqXHR object in an ajax request. It can also be considered as an XMLHTTPRequest object (inherited or encapsulated ), however, this is not the case in jsonp requests. It cannot bring us the most useful information such as XMLHTTPRequest: it lacks the Request status information of XMLHTTPRequest, so it cannot trigger most callback functions, for example, error, complete, etc. (jQuery1.9.0), and the success function that can be called back should be triggered by the load event marked by the script, which is also different from the mechanism that ajax relies on the XMLHTTPRequest status. After testing, zepto (v1.1.3), originated from jQuery, has an error in the jsonp request. For example, when the header returns a 401 error when loading the js document, the error function is executed, however, the jqXHR parameter of this function is also not an authentic jqXHR type, and cannot even be used to obtain the response header information. In this case, we are only notified that an error occurred in a link, but does not know the specific error information. Similar to scenarios where the response header carries useful information, it is not recommended for bloggers to use jsonp. It can be said that the premise of using jsonp is that, apart from non-business exceptions such as network exceptions, all business exceptions (In summary, all exceptions thrown from the server receiving requests to the response returned) must be directly returned to the client in the form of request results, this facilitates client callback analysis.

Thank you for reading this article. I hope it will help you. Thank you for your support for this site!

Related Article

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.