JSONP cross-domain access implementation

An introduction

  • JSONP (JSON with Padding) is a method for resolving cross-domain requests, which allows data from one domain to be requested from another domain. JSONP takes advantage of the characteristics of the '<script>' tag to load JavaScript files containing JSON data by dynamically creating <script> tags.

    1.Basic working principle of JSONP

    1. The client (browser) creates a <script> tag, sets its src attribute to the URL containing JSON data in the target domain, and specifies a callback function name as a query parameter

    example

    <script src="http://example.com/data?callback=myCallback"></script>

    2. After receiving the request, the target domain server passes the JSON data as a parameter to the callback function and returns it to the client as JavaScript code.

    example

    myCallback({"name": "John", "age": 30});

    3. The client defines the callback function myCakkback. When receiving the returned javascript code, the function is automatically executed and uses JSON data as a parameter.

    function myCallback(data) { 
        // Process the returned JSON data 
        console.log(data.name); 
        console.log(data.age); 
      }

    In this way, JSONP can bypass the browser's same-origin policy restrictions and achieve cross-domain requests and data acquisition.

2. Generate JSON response

1.PHP code

Generate PHP code on 192.168.120.84 and name it list-json.php

<?php 
​//
//Connect to the database and access 
$conn = new mysqli('127.0.0.1','root','123456','learn') or die("Database connection failed."); 
$conn ->set_charset('utf8'); 
$sql = "select * from xssdata"; 
$result = $conn->query($sql); 
//
Output JSON data to the page 
$json = json_encode($result->fetch_all (MYSQLI_ASSOC)); 
echo $json; 
​$
conn->close(); 
​?
>
2. Browser access

Access directly in the browser and the following data will be obtained

 

3. Access using AJAX on another page

1. Build a new page at 192.168.120.84, name it list-json.html, and send a request to list-json.php
<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 
    <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
    < title>Document</title> 
    <script type="text/javascript"> 
        var listUrl = 'http://192.168.120.84/jsonp/list-json.php'; 
        //Instantiate XMLHttpRequest for sending AJAX request 
        xmlhttp = new XMLHttpRequest(); 
        var count = 0; 
        //When the request status changes, trigger the execution code 
        xmlhttp.onreadystatechange=function(){ 
            if(xmlhttp.readyState == 4 && xmlhttp.status==200){ 
                //Get the response of the request and extract the Token through the response regularity 
                var text = xmlhttp.responseText 
                alert(text) 
            }
        };
        xmlhttp.open("GET",listUrl,false);
        xmlhttp.send();
    </script>
</head>
<body>
​
2. Access list-json.php in the browser, and the normal pop-up window will appear.

 

3. Save list-json.php to the 192.168.120.51 server

(1) Access method

Save the code of list-json.php to the 192.168.120.51 server, access the address directly in the browser, and confirm that it can be accessed normally (be careful to change the database connection)

(2) Access the list-json.html page on the 84 server

Change the listUrl address of list-json.html to the address of the 51 server. At this time, when accessed in the browser, the pop-up window will not be available. Open F12 and see the output of the console as follows

 

The above are the problems that exist across domains.

4. Use JSONP to solve cross-domain access

1. Modify the list-json.php of 51 server

Replace 
echo $json; 
with 
echo $_GET['callback']."(".$json.")"; //Output the callback function to the front end

2. Modify the list-json.html page on the 84 server to:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script>
        //先定义好一个JS函数
        function test(args){
            alert(JSON.stringify(args));
        }
    </script>
    <script src="http://192.168.120.51/list-json.php?callback=test"></script>
</head>
<body>
​

Visit http://192.168.120.84/jsonp/list-json.html again to achieve normal access

 

Principle: The script tag is not affected by the same-origin policy, and the value is passed to the page as an actual parameter through the callback.

Five JSONP cross-domain key points

1. After list-json.php achieves cross-domain access, any website can access its data. As long as you know its parameter name $_GRT['callback'], and perform function callbacks in JS, you can complete the access.

2. Another point is to put <script src="192.168.120.51/list-json.php?callback=test"></script> in the <script> tag, because this tag allows cross-domain access

Guess you like

Origin blog.csdn.net/m0_73896875/article/details/131685749