<!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="http://www.runoob.com/try/ajax/jsonp.php?jsoncallback=callbackFunction"></script>
</body>
</html>
<?php
header('Content-type: application/json');
//獲取回調函數名
$jsoncallback = htmlspecialchars($_REQUEST ['jsoncallback']);
//json數據
$json_data = '["customername1","customername2"]';
//輸出jsonp格式的數據
echo $jsoncallback . "(" . $json_data . ")";
?>
你看輸出不就知道了。。jsonp就是一段js代碼,一般格式就是callback(數據),當然數據也可以改為其他參數
callbackFunction(["customername1","customername2"])
由於沒有傳遞第二個參數,所以methodName是undefined,如果回調裡面使用到methodName沒判斷是否有值直接用就會報錯了