js-JSONP

js-JSONP directory


Preface

  • JSONPJSON with PaddingShorthand for yes , weba JSONvariant popular on services
  • Wrapped in a function call
  • Format: callback and data
  • Callback: the function called after the page receives the response, dynamically specified
  • Data: parameters passed to the callback JSONdata

http://xxx/?callback=handleResponse

  • Create dynamically <script>and specify cross-domain urlimplementation

Code display

main.js

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;
}

jsonp.php

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

Client complete page code

<!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.runoob.com/try/ajax/jsonp.php?jsoncallback=callbackFunction"></script>
</body>
</html>

Guess you like

Origin blog.csdn.net/u013362192/article/details/114994732
Recommended