? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?jsonp的使用
<?phpheader('Content-type: application/json');//獲取回調(diào)函數(shù)名$jsoncallback = htmlspecialchars($_REQUEST ['jsoncallback']);//json數(shù)據(jù)$json_data = '["customername1","customername2"]';//輸出jsonp格式的數(shù)據(jù)echo $jsoncallback . "(" . $json_data . ")";?>
2. 客戶端實現(xiàn) callbackFunction 函數(shù)
<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>
頁面展示
<div id="divCustomers"></div>
客戶端頁面完整代碼
<!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>
jQuery 使用 JSONP
以上代碼可以使用 jQuery 代碼實例:
<!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>