2020-03-19

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?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>

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容