JSONP
-
What is the json
- JSONP (JSON with Padding) is a “usage mode” of JSON that can be used to solve the problem of cross-domain data access in mainstream browsers.
-
Implementation principle of JSONP
- Web pages cannot request non-same-origin interface data through Ajax because of the browser same-origin policy.
- The script tag is not affected by the browser’s same-origin policy and can request non-same-origin JS script data through the SRC attribute.
- Receive the data back from the cross-domain interface in the form of a function call.
-
To realize the json
-
Define a SUCCESS callback function.
<script> function success(data){ console.log("Get the data"); console.log(data) } </script> Copy the code
-
Request interface data via the script tag.
<script src="http://ajax.frontend.itheima.net:3006/api/jsonp?callback=success&name=silly&sge=20"></script> Copy the code
-
-
The disadvantage of the json
- Only GET data requests are supported, POET data requests are not supported.
- JSONP has nothing to do with Ajax and does not use the XMLHttpRequest object.
-
The json in jQuery
-
JQuery provides the $.ajax() function to initiate a JSONP data request
$.ajax({ url:'http://ajax.frontend.itheima.net:3006/api/jsonp?callback=success&name=silly&sge=20'.// Initiate a JSONP request dataType:'jsonp'.success:function(res){ console.log(res.data); }});Copy the code
-
The json sample
Request Github information
Encapsulate a function to make the request