[Web] How does JSONP work?

JSONP is a method to transfer JSON data without considering cross-domain issues.

JSONP does not use XMLHttpRequest objects.

JSONP uses the <script> tag instead.

Introduction to JSONP

JSONP refers to JSON with Padding.

Requesting files from another domain can cause problems due to cross-domain policies.

Requesting external scripts from another domain does not have this problem.

JSONP takes advantage of this and uses script tags instead of XMLHttpRequest objects.

<script src="demo_jsonp.php">
JSONP application

Server-side JSONP format data

If the customer wants to visit: https://www.runoob.com/try/ajax/jsonp.php?jsoncallback=callbackFunction.

Assume that the customer expects to return data: ["customername1", "customername2"].

The data actually returned to the client is displayed as: callbackFunction (["customername1", "customername2"]).

The server file jsonp.php code is:

<?php
header('Content-type: application/json');
//获取回调函数名
$jsoncallback = htmlspecialchars($_REQUEST ['jsoncallback']);
//json数据
$json_data = '["customername1","customername2"]';
//输出jsonp格式的数据
echo $jsoncallback . "(" . $json_data . ")";
?>

Client:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JSONP 实例</title>
</head>
<body>
<div id="divCustomers"></div>
<script type="text/javascript">
function callbackFunction(result, methodName)
{
    var html = '<ul>';
    for(var i = 0; i < result.length; i++)
    {
        html += '<li>' + result[i] + '</li>';
    }
    html += '</ul>';
    document.getElementById('divCustomers').innerHTML = html;
}
</script>
<script type="text/javascript" src="https://www.xxxx.com/try/ajax/jsonp.php?jsoncallback=callbackFunction"></script>
</body>
</html>

jQuery uses JSONP:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>JSONP 实例</title>
    <script src="https://cdn.static.runoob.com/libs/jquery/1.8.3/jquery.js"></script>    
</head>
<body>
<div id="divCustomers"></div>
<script>
$.getJSON("https://www.runoob.com/try/ajax/jsonp.php?jsoncallback=?", function(data) {
    
    var html = '<ul>';
    for(var i = 0; i < data.length; i++)
    {
        html += '<li>' + data[i] + '</li>';
    }
    html += '</ul>';
    
    $('#divCustomers').html(html); 
});
</script>
</body>
</html>
Published 395 original articles · Liked 14 · Visits 100,000+

Guess you like

Origin blog.csdn.net/LU_ZHAO/article/details/105434609