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 on the website of, 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=""></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.


Main code of jsonptest.html page

<script src=""></script>  
            <script type="text/javascript">  
                           url : "http://ip/jsonpreturn.php ", / / remote IP address or domain name
                           type:"post",  // Even if you use post, it will become get mode in browser
                           timeout: 5000,  
                           error:function(XHR, textStatus, errorThrown){  
                               console.log('error: ' + textStatus);  
                               console.log('error: ' + errorThrown);  

jsonpreturn.php main code

    $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