Cross domain implementation of jsonp+php

Cross domain principle of jsonp

There is no cross domain limit for < script > tags

The difference between json and json

json is a text-based way of data exchange, or a format for describing data.

var person = {
    "name": "test",
    "age": "25",
    "sex": "male"
};
 
var data = [1, 2, 3, 4, 5];

jsonp is an unofficial cross domain data interaction protocol, which allows users to pass a callback parameter to the server, and then the server will wrap the json data as function name when returning data, so that the client can customize its own function to automatically process the returned data.
For example, I refer to a b.js of b.com on the website of a.com, but cross domain reference does not produce errors, which means that when calling JS file, it is not affected by cross domain.

<script type="text/javascript" src="http://www.b.com/b.js"></script>

Then we add the following code in b.js to see if it can be executed

alert("I from b");

Make sure it can be executed.

Request method

If you use jsonp for cross domain requests, the only way you can use is to get, and you can't receive $_postrequest data in the php background.

Example

Main code of jsonptest.html page

<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>  
            <script type="text/javascript">  
                $(function(){  
                      $.ajax({  
                           url : "http://ip/jsonpreturn.php ", / / remote IP address or domain name
                           dataType:"jsonp",  
                           data:{  
                               "name":"xiaoming",  
                               "pass":"123456"  
                           },  
                           type:"post",  // Even if you use post, it will become get mode in browser
                           jsonp:"callback",  
                           timeout: 5000,  
                           success:function(data){  
                                console.log(data); 
                           },  
                           error:function(XHR, textStatus, errorThrown){  
                               console.log('error: ' + textStatus);  
                               console.log('error: ' + errorThrown);  
                           }  
                      });  
                });  
            </script>  

jsonpreturn.php main code

<?php  
    $name = $_GET['name'];  // _POST cannot receive data
    $pass = $_GET['pass'];  
      
    $jsonp = $_GET['callback'];//get receives the function name automatically generated by JSON  
      
    $arr = array(  
        'name' => $name,  
        'pass' => $pass 
    );  
    echo $jsonp.'('. json_encode($arr). ')'; //json function name package json data  
?>  

Keywords: JSON PHP Javascript JQuery

Added by mcrbids on Fri, 01 May 2020 18:31:35 +0300