Understanding of the JSONP principle

Source: Internet
Author: User
Tags script tag

For JavaScript programmers, sending AJAX requests for background data and then stitching data and templates into string rendering back to the DOM to implement a no-refresh update page is pro. But it is well known that Ajax has a bad, that is, can not transfer data across domains, and cross-domain transmission is sometimes necessary, for example, we may need to call third-party web site to provide some of the API to obtain certain information, provided to our site users.   For example, to develop a weather app, you might need to invoke a third-party weather API, which would inevitably involve cross-domain request data, because we can't build a weather API ourselves to develop a weather app. In rare cases, if a cors mechanism is set up on a server in a third-party web site, the request can be sent directly using AJAX. In most cases, however, third-party sites are less generous because they involve security issues and it is not possible to allow anyone to freely invoke the interface of their website. This time Jsonp was born.   have such tags in html, they all have a src attribute, the value of the SRC attribute is a link, and when the label is parsed into the DOM, it begins to download the resource from the SRC attribute to this document, for example, The IMG tag setting src will automatically download the resource from the link of the SRC attribute, and the downloaded resource will be parsed into the DOM by the browser, and the IFRAME element with the src attribute will download a webpage from the SRC link. The script element that sets the SRC attribute will also automatically download the JavaScript code from the SRC link and execute it, and the DOM itself is not refreshed in the process, and what's more, the link to the SRC attribute is not bound to the same domain at all. This principle is the cornerstone of the realization of JSONP.   However, we want to use it to achieve cross-domain is also very difficult. This src attribute of the element loading and general Ajax requests have a very different, recall, in a typical AJAX request, we can fully control the request process, we can open the specified Web page, can set the request header, can specify the mimetype of the response, the key is , we can get the response data from the ResponseText property of the Xhr object, then stitch the template and render the DOM. But in the IMG, IFRAME, script these tags, we are deprived of control, we set the SRC attribute, the browser is responsible for sending requests, the server returns the response is directly loaded back to the DOM, we do not interfere with the opportunity to modify the data. What about  ? It's like launching a spaceship to a distant deep space, and when the ship is dozens of light-years away, we're less likely to send real-time control signals from the ground, and better yet, write the instructions ahead of the flight.On board, let it execute automatically.   As with the spaceship example, a typical JSONP process is to create a script tag, set the SRC attribute, which includes the address of the target API, our query string querystring, The most important thing in QueryString is our "instruction", because after the script tag src returns, we do not control the result of the return, so it is better to let the server return to do what we want to do. This "instruction" is the "P" in Jsonp.   Lift a chestnut: 1. I need some data, like the weather data, as I said earlier, so I construct the query URL.
var script = document.createelement (' script '); script.src = ' Www.weather.fake/get/?province=hubei&city=wuhan &callback=instruction ';d ocument.getelementsbytagname (' head ') [0].appendchild (script);
Write the instruction first, that is, the callback function instruction (data) {

2.weather.fake's server received my request and found the data from the database. See, there is an instruction, so it executes the instruction instruction. It's very advanced, which is actually wrapping the returned data in the instruction function (Jsonp's p,padding). The server then returns a thing like this:
Response.jsinstruction ({
"City": "Wuhan",
"Weather": "Cloudy"
 3. Server-side Writeheader settings and browser-side accept settings will ensure that the returned things will be interpreted by the browser as a JS file, so we have written a good command instruction function is executed, the entire JSONP process is complete.   points to note:  1. The returned JS file is executed at the global scope, so make sure you write the callback function instruction in the global scope.   2. Here's callback=instruction. Among them, callback is just a common querystring, is you and the server beforehand agreed, different API provider, the name is also different, some may be called CB, and so on. As for instruction, you write what you write, but make sure you have the same name as the callback handler you write. I'm writing instruction here for the sake of understanding.  : What is the danger of Ajax cross-domain? Some people say that the ban on Ajax cross-domain is to prevent attackers from using it to send sensitive information (such as cookies, etc.) to their servers, which is obviously wrong. For a website that has been injected with an attack code, an attacker who simply wants to send information to his or her own server, even without Ajax, can use an IMG tag to send data directly to his server, and creating an IMG tag can be much simpler than writing a complete Ajax process. , there is no need to selectmen, that is, one-way GET request Ajax has no advantage.   Why limit Ajax, because it's too powerful. Look at the cors mechanism, which specifies the server-side accept whitelist. That is, the server determines which customers can be accepted to request data from it. Explains that cross-domain throttling is primarily for server-side security.   generally can be done with SRC, Ajax can do, Ajax can do the SRC but not necessarily can do. For example SRC can only initiate a GET request, but Ajax can initiate any type of request.   For a chestnut, a blog site of the deletion of the article feature API may have to use the Delete method to send a request to execute, this time if the attacker can only construct the SRC request is powerless, but Ajax is easy to simulate user action. It is important to prohibit cross-domain at this time.   Specific process: Suppose my attack site is www.evil.com. A blog site that allows Cors to transmit Ajax across domains is www.blog.com. In this blog site, when the user clicks the Delete button, a delete request is sent to the server. The specific: Www.blog.com/user/delete (? id=10000) (because it is the Delete method, the QueryString is actually not attached to the URL, for illustrative purposes.) This time, if the user visits my Evil.com website, and I write Ajax in my website's script:
$.ajax ({    URL: ' Www.blog.com/user/delete ',    method: ' Delete ',    data:{id:10000},})
This is successful, because when sending Ajax, will automatically bring the user in the www.blog.com of the cookie, and the request method is legitimate, so completely can obtain the trust of the blog.com server, you can unknowingly delete the user wrote on the blog.com article.

Understanding of the JSONP principle

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.