The src attribute of the <script> element can set the URL and initiate an HTTP GET request, using the <script> Element Implementation script operation HTTP can communicate across domains without restriction and homology policy. Typically, when using a <script> Ajax transport protocol, the server responds with a JSON-encoded data format that can be automatically decoded by the JavaScript parser when the script is executed. Because it uses the JSON data format, this AJAX transport protocol is also called "JSONP". So using JSONP technology, you just need to set the SRC attribute of <script> and insert it into the document, and then the browser sends an HTTP request to the URL that executes the SRC attribute below.
When using the <script> element to invoke data, the response content must be wrapped in a JavaScript function name and parenthesis (that is, it can only serve as an argument to the functions) rather than a direct JSON data:
Copy Code code as follows:
Response
[1, 2, {"Hello", "World"}]
)
In order to be feasible, we have to tell the service in some way that it is calling from a <script> element and must return a JSONP response instead of a normal JSON, which can be implemented by adding a query parameter to the URL: for example, append "? JSON" (or &json)
In practice, services that support JSONP do not enforce the name of the callback function that the client must implement, such as response. Instead, they use the value of the query parameter to allow the client to specify a function name and then use the function name to populate the response.
Copy code code as follows:
//Send a JSON request based on the URL specified
//then pass the parsed response data to the callback function
// Add a query parameter named Jsonp in the URL to specify the name of the callback function for the request
function Getjsonp (URL, callback) {
//////////////////Create a unique callback function name for this request
Var cbnum = "CB" +getjsonp.counter++;
var cbname = "Getjsonp." +cbnum; As a property of the JSONP function
//Add the callback function name to the URL Query section as form encoding
if (Url.indexof ("?") = = 1) {
URL = "? jsonp=" +cbname; The
}else{
url = "&jsonp=" +cbname;
}
//create <script> send request
var script = document.createelement ("script");
//Defines the callback function executed by the script
Getjsonp[cbnum] = function (response) {
try{
Callback (response);//Process Response
}
F inally{
//Deletes the function and removes the corresponding script element
Delete Getjsonp[cbnum];
Script.parentNode.removeChild (script);
}
//immediately triggers the HTTP request
Script.src = URL;
Document.body.appendChild (script);
}
Getjsonp.counter = 0;