"Jsonp"

Source: Internet
Author: User

One, homologous strategy

To understand cross-domain, first look at the "same-origin policy." The so-called homology refers to the same domain name, protocol, and port. The so-called "homologous strategy", simply said, is based on security considerations, the current domain can not access the other domain things.

Some common examples of homologous homology are referenced in the following table:

Under the same-Origin policy, a page under a server cannot obtain data outside of that server. For example, we use Ajax on our own website to obtain the interface data provided by HTTPS://DEVELOPERS.DOUBAN.COM/WIKI/?TITLE=API_V2 on the watercress. Here we take the search book as an example, the parameter link is: Https://api.douban.com/v2/book/search?q=javascript&count=1, the data in the link is in JSON format, as follows:

I use the following code to access the data:

<! DOCTYPE html><Htmllang="EN" ><Head><Metacharset="UTF-8" ><Title>ajax</Title></Head><Body><DivId="Mydiv" ><buttonId="BTN" > click</Button></Div></Body><ScriptType="Text/javascript" >Window.onload =function() {var obtn = document.getElementById (' btn '); Obtn.onclick = function() { var xhr = new XMLHttpRequest (); xhr.onreadystatechange = function() { if (xhr.readystate = = 4 && xhr.status = = ) {alert (xhr.responsetext);}}; Xhr.open (' get ', ' Https://api.douban.com/v2/book/search?q=javascript&count=1 ', true); Xhr.send ();};}; </script></html>            

The above program will run with an error:

But the SRC (get the picture), <link> the href (get CSS), <script> the SRC (get JavaScript) These three are not consistent with the same-origin policy, they can get data across domains. The JSONP to be introduced here is the use <script> of SRC to achieve cross-domain data acquisition.

Second, JSONP

JSONP is a shorthand for JSON with padding (filled JSON or parametric json).

Jsonp the principle of implementing cross-domain requests is simply to create <script> tags dynamically, and then use <script> src to get data across domains without being constrained by the same-origin policy.

JSONP consists of two parts: the callback function and the data. A callback function is a function that should be called in the page when the response arrives. The name of the callback function is typically specified in the request. The data is the JSON data that is passed into the callback function.

Dynamically create the <script> label, set its SRC, and the callback function is set in SRC:

var script = document.createElement("script");script.src = "https://api.douban.com/v2/book/search?q=javascript&count=1&callback=handleResponse";document.body.insertBefore(script, document.body.firstChild);

In the page, the returned JSON is passed as a parameter to the callback function, and we manipulate the data through the callback function.

function handleResponse(response){    // 对response数据进行操作代码}

Understand the basic use of JSONP, we implement the above through Ajax call Watercress interface requirements, the implementation code is as follows:

<! DOCTYPE html><Htmllang="EN" ><Head><Metacharset="UTF-8" ><Title>jsonp Implementing Cross-Domain 2</Title></Head><Body><DivId="Mydiv" ><buttonId="BTN" > click</Button></Div></Body><ScriptType="Text/javascript" > functionHandleresponse(response) {Console.log (response);}</Script><Scripttype= "Text/javascript" > Window.onload = function () { Span class= "Hljs-keyword" >var obtn = document.getElementById ( ' btn '); Obtn.onclick = function () { var script = document.createelement ( "https://api.douban.com/v2/book/search?q=javascript&count=1&callback= Handleresponse "; Document.body.insertBefore (script, document.body.firstChild); };}; </script></ HTML>             

In the console, we can view the returned response data format as JSON object format, specifically need to take out which parameters, can according to their own needs:

Jsonp is still a relatively popular cross-domain approach, although JSONP is convenient to use, but there are some problems:
First, JSONP is the load code execution from the other domain. If the other domains are unsafe, it is likely that some malicious code will be entrained in the response, and there is no way to pursue this at this point except to completely abandon the JSONP call. So when using a WEB service that is not your own operation, make sure it is safe and secure.

Second, it is not easy to determine whether JSONP requests fail. Although HTML5 <script> adds an onerror event handler to the element, it is not currently supported by any browsers. To do this, the developer had to use a timer to detect whether a response was received within the specified time.

Second, jquery package Jsonp

For developers who often use jquery, note that $.ajax there is a property in the jquery package dataType , and if you set this property dataType:"jsonp" , you can implement JSONP across domains. One thing to understand is that while jquery encapsulates Jsonp $.ajax , it's essentially $.ajax different.

The $.ajax implementation of cross-domain code through jquery is referenced below:

<! DOCTYPE html><Htmllang="EN" ><Head><Metacharset="UTF-8" ><Title>jquery Implementation JSONP</Title></Head><Body><DivId="Mydiv" ><buttonId="BTN" > click</Button></Div></Body><ScriptType="Text/javascript"Src="Https://code.jquery.com/jquery-3.1.0.min.js" ></Script><ScriptType="Text/javascript" >$(function(){ $("#btn"). Click (function() {$.ajax ({async:True, URL:"Https://api.douban.com/v2/book/search", type: "GET", DataType: // The returned data type is set to JSONP mode Jsonp:  ' callback ', //specify a query parameter name to override the default JSONP Callback Parameter name callback Jsonpcallback:  ' Handleresponse ', // Set callback function name data: {q:  "JavaScript", Count: 1}, Success: function", State is: ' + xhr.statustext); Console.log (response ); } }); }); }); </script></ HTML>             

The final result is the same as the <script> result of JavaScript being dynamically tagged.

by $.getjson ()

Use Getjson to achieve, as long as the address to add callback=? parameters, the reference code is as follows:

$.getJSON("https://api.douban.com/v2/book/search?q=javascript&count=1&callback=?", function(data){                console.log(data);            });

This also enables cross-domain functionality.

"Jsonp"

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.