現在很多廠商比如,百度、谷歌在調用api接口時早已開始使用json數據。
但是古老的XMLHttpRequest設計時,為了安全性,不能使用跨站數據(就是調用其它的網站的數據)
如果需要訪問由遠程服務器上一個web服務托管的json數據,則要使用JSONP。
假設,我要進行百度地圖坐標轉換,這是文檔http://developer.baidu.com/map/changeposition.htm
運行示例 http://api.map.baidu.com/geoconv/v1/?coords=114.21892734521,29.575429778924;114.21892734521,29.575429778924&from=1&to=1
瀏覽器打開得到返回值 (注意當前返回錯誤,本文只是隨便找個例子用來講解)
{"status":22,"message":"param error:to illegal, not support such coord type","result":[]}
那么我們該如何來讓我們的頁面程序獲取這個值呢?
在示例鏈接中加入
callback=GetValue
然后新建html頁面
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script>
var getVal;
function GetValue(Value)
{
getVal = Value;
alert("ok");
}
</script>
</head>
<body>
<script src="http://api.map.baidu.com/geoconv/v1/?coords=114.21892734521,29.575429778924;114.21892734521,29.575429778924&from=1&to=1&callback=GetValue">
</script>
</body>
</html>
!注意html頁面中新建的GetValue函數
通過<script>標簽調用示例鏈接產生GetValue值時就會彈窗
然后通過火狐firebug進入控制臺查看GetValue的參數傳遞給getVal的值
Object { status=22, message="param error:to illegal, ...support such coord type", result=[0]}