js implements JSONP/backend interface settings in 2 spanning requests to run spanning headers

Due to the browser same-origin policy, ajax requests from js of domain a to domain b will be prohibited. There are 2 ways for JS to achieve cross access interface.

1. The back-end interface sets the header header that allows spanning.

public function index(){ 
//header('Access-Control-Allow-Origin:*'); //Supports full domain name access, which is not safe. After deployment, it needs to be fixed to the client URL
header('Access-Control-Allow -Origin:http://www.example-a.com'); //The url with the protocol is set, not a domain name. Multiple urls can be set, separated by commas
     echo json_encode(['name'=>'lucy']);
}

  

  The client can make a normal ajax request.

 

2. The client requests through jsonp, and the server does not need to set the spanning header. The principle of jsonp will not be mentioned here, and you can find additional information. A specific method of implementation is given below.

Client request, take jquery implementation as an example

 

<script type="text/javascript">
    $(document).ready(function(){
        $.ajax({
            type : "get",
            async: false,
            url : "http://www.example-a.com/api.php?id=1",
            dataType: "jsonp",
            jsonp:"callback", //Request php parameter name
            //jsonpCallback: "jsonhandle",//The callback function to be executed, (in jquery, this parameter can be omitted, jquery will randomly generate a name)
            success : function(data) {
                console.log(data);
            }
        });
    });
</script>

   

api.php

<?php
     //Complete business logic to get data
     echo $_GET['callback']. '('. json_encode($data). ')'; //$_GET['callback'] is the 'jsonp' parameter of the jsonp request in the jquery above
?>

 

 

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324613284&siteId=291194637