In the past, we only knew that ajax cross-origin can only be solved through the jsonp method. When uploading a video locally recently, we need to upload the video to Youku and youtube. If we use the post method directly, you can only see the upload progress below the browser, and the user experience is poor. If you use ajax to upload, you can customize the upload progress and display the upload speed. However, due to the upload to a third-party video service provider, the first problem is cross-origin.
CORS can solve this problem.
CORS is more advanced, convenient, and reliable than JSONP.
1,JSONP can only implement GET requestsAnd CORS supports all types of HTTP requests.
For example, if the slave server (http://www.a.com/user? Id = 123) the obtained data is as follows:
{"Id": 123, "name": James, "age": 17}
So, request using JSONP method (http://www.a.com/user? Id = 123? Callback = foo) data will be as follows:
Foo ({"id": 123, "name": Zhang San, "age": 17}); of course, if the server considers more adequately, the returned data may be as follows:
Try {foo ({"id": 123, "name": Zhang San, "age": 17});} catch (e ){}
At this time we just need to define a foo () function and dynamically create a script tag so that its src attribute is http://www.a.com/user? Id = 123? Callback = foo:
<Script type = "text/javascript" src = "http://www.a.com/user? Id = 123? Callback = foo "> </script>
You can use the foo function to call the returned data.
How to Use JSONP in jQuery to obtain data across domains
The first method is to set ype to 'jsonp' In the ajax function ':
$. Ajax ({2. dataType: 'jsonp', 3.url: 'HTTP: // www.a.com/user? Id = 123 ', 4. success: function (data) {5. // process data 6 .} 7 .}); the second method is to use getJSON to add callback =? Parameters:
$. GetJSON ('HTTP: // www.a.com/user? Id = 123 & callback =? ', Function (data) {2. // process data 3.}); you can also simply use the getScript method:
// You can also define the foo method outside the function.
Function foo (data ){
/Process data}
$. GetScript ('HTTP: // www.a.com/user? Id = 123 & callback = foo ');
2. With CORS, developers can use common XMLHttpRequest to initiate requests and obtain data, which provides better error handling than JSONP.
3. JSONP is mainly supported by old browsers, which often do not support CORS, and most modern browsers already support CORS.
In PHP: header ("" Access-Control-Allow-Origin :*"");
In html: <meta http-equiv = "Access-Control-Allow-Origin" content = "*">
If CORS contains a 302 jump, the URL after the 302 jump also contains the CORS header request.
Currently, both IE8 and other mainstream browsers support CORS. We believe this technology will be very useful in the future.