Home > Article > Web Front-end > The perfect solution to cross-domain requests (JSONP, CORS) (picture and text tutorial, with code)
Now I will bring you a perfect solution for cross-domain requests (JSONP, CORS). Let me share it with you now and give it as a reference for everyone.
A well-known problem is that Ajax directly requests ordinary files, which causes cross-domain unauthorized access. Solutions include JSONP, Flash, etc.
JSONP
We found that when calling js files on a Web page, it is not affected by whether it is cross-domain or not. Anyone with the "src" attribute All tags have cross-domain capabilities, such as 3f1c4e4b6b16bbbd69b2ee476dc4f83a, a1f02c36ba31691bcfe87b2722de723b, d5ba1642137c3f32f4f4493ae923989c. That is to say, if you want to access data across domains, the server can only put the data in js format files. It happens that we know that JSON can describe complex data concisely, and JSON is also natively supported by js, so the client can process data in this format almost as desired. Then the client can call the dynamically generated js format file on the cross-domain server in exactly the same way as calling the script. After the client successfully calls the JSON file, it obtains the data it needs. This forms the basic concept of JSONP. Users are allowed to pass a callback parameter to the server, and then when the server returns data, it will use this callback parameter as a function name to wrap the JSON data, so that the client can customize its own function to automatically process the returned data.
jQuery supports JSONP calling. After specifying the callback function name in another domain name, you can use the following form to load JSON data.
url?callback=? jQuery.getJSON(url + "&callback=?", function(data) { alert(data.a + data.b); });
Of course the server must also provide JSONP support. In fact, it only needs to provide the params of read and write callback.
Cross-Origin Resource Sharing (CORS)
CORS is more advanced, convenient and reliable than JSONP.
1. JSONP can only implement GET requests, while CORS supports all types of HTTP requests.Header set Access-Control-Allow-Origin *
Access-Control-Allow-Origin: http://www.jb51.net
Focus on analyzing the techniques for rewriting the alert() method in JavaScript
Basic syntax and variables of JavaScript Explain
Javascript simulation overloading, detailed answers to rewriting the toString method
The above is the detailed content of The perfect solution to cross-domain requests (JSONP, CORS) (picture and text tutorial, with code). For more information, please follow other related articles on the PHP Chinese website!