1. The implementation principle of jsonp is to use script tags to obtain the characteristics of different source resources to achieve the purpose of cross-domain access to a resource. The specific behavior is as follows:
Create a script tag, write the request address into its src attribute, and insert the script external link into the head tag;
Declare a callback function callback, the function name is consistent with the request address;
The content of the request address is an execution function callback that takes a json object as a parameter;
When the script resource is loaded, the callback starts executing and the json data is output.
jsonp is actually json padding, and the function that wraps it outside the json data is padding.
// 简单的mock jsonpvar mockJsonp = function(url) {var ele = document.createElement('script');var head = document.getElementsByTagName('head')[0]; ele.src = url; head.appendChild(ele); } mockJsonp('./index.js');function callback(data){ console.log(data); }// index.jscallback("name": "xxx", "age": "20");
2. When the ajax request data format in jq is jsonp, the following operations will occur: first construct a script tag, and then register an onload callback, Finally, insert the constructed script tag into it; after the insert is completed, the onload callback will be triggered, and the previously inserted script tag will be removed. The code callback(200, "success") is actually the success callback function that triggers ajax's jsonp successfully. The callback function is actually a done function.
3. Cross-domain jsonp can only be a get request. When jq encapsulates jsonp cross-domain, whether we specify get or post, it will be replaced by a get request.
4. Other cross-domain methods
cors (Cross-Origin Resource Sharing) cross-domain resource sharing, set Access-Control-Allow-Origin on the server side, if you browse If the server detects the corresponding settings, it will allow access;
Modify document.domain and set the document.domain of the subdomain and the main domain to the same main domain;
window.name, each page has read and write permissions to window.name, window.name persists in all pages loaded in a window;
window.postMessage
The above is the detailed content of jsonp implementation principle analysis. For more information, please follow other related articles on the PHP Chinese website!