JSONP

  1. 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.
  2. 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.
  3. To realize the json

    1. Define a SUCCESS callback function.

      <script>
      	function success(data){
              console.log("Get the data");
              console.log(data)
          }
      </script>
      Copy the code
    2. 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
  4. 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.
  5. 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