JSONP 編程
我將向大家介紹 JSONP 的知識。
Jsonp(JSON with Padding) 是 json 的一種"使用模式",可以讓網頁從別的域名(網站)那獲取資料,即跨域讀取數據。
為什麼我們從不同的域(網站)訪問數據需要一個特殊的技術(JSONP )呢?這是因為同源策略。
同源策略,它是由Netscape提出的一個著名的安全策略,現在所有支持JavaScript 的瀏覽器都會使用這個策略。
JSONP 應用
1. 服務端JSONP格式數據
如客戶想訪問 : http://www.run.com/try/ajax/jsonp.php?jsonp=callbackFunction。
假設客戶期望返回JSON數據:["customername1","customername2"]。
真正返回到客戶端的數據顯示為: callbackFunction(["customername1","customername2"])。
服務端文件jsonp.php代碼為:
jsonp.php 文件代碼
<?phpheader("Content-type: application/json");//獲取回調函數名$jsoncallback = htmlspecialchars($_REQUEST["jsoncallback"]);//json數據$json_data = "["customername1","customername2"]";//輸出jsonp格式的數據echo$jsoncallback . "(" . $json_data . ")";?>
2. 客戶端實現 callbackFunction 函數
<scripttype="text/javascript">functioncallbackFunction(result, methodName){varhtml = "<ul>"; for(vari = 0; i < result.length; i++){html += "<li>" + result[i] + "</li>"; }html += "</ul>"; document.getElementById("divCustomers").innerHTML = html;}</script>
頁面展示
<divid="divCustomers"></div>
客戶端頁面完整代碼
<!DOCTYPEhtml><html><head><metacharset="utf-8"><title>JSONP 實例</title></head><body><divid="divCustomers"></div><scripttype="text/javascript">
functioncallbackFunction(result, methodName){varhtml = "<ul>"; for(vari = 0; i < result.length; i++){html += "<li>" + result[i] + "</li>"; }html += "</ul>"; document.getElementById("divCustomers").innerHTML = html; }
</script><scripttype="text/javascript"src="http://www.runoob.com/try/ajax/jsonp.php?jsoncallback=callbackFunction"></script></body></html>
jQuery 使用 JSONP
以上代碼可以使用 jQuery 代碼實例:
<!DOCTYPEhtml><html><head><metacharset="utf-8"><title>JSONP 實例</title><scriptsrc="http://cdn.static.runoob.com/libs/jquery/1.8.3/jquery.js"></script></head><body><divid="divCustomers"></div><script>
$.getJSON("http://www.runoob.com/try/ajax/jsonp.php?jsoncallback=?", function(data){varhtml = "<ul>"; for(vari = 0; i < data.length; i++){html += "<li>" + data[i] + "</li>"; }html += "</ul>";
$("#divCustomers").html(html);
});
</script></body></html>
TAG:程序員小新人學習 |