現(xiàn)在很多廠商比如,百度、谷歌在調(diào)用api接口時早已開始使用json數(shù)據(jù)。
但是古老的XMLHttpRequest設(shè)計時,為了安全性,不能使用跨站數(shù)據(jù)(就是調(diào)用其它的網(wǎng)站的數(shù)據(jù))
如果需要訪問由遠(yuǎn)程服務(wù)器上一個web服務(wù)托管的json數(shù)據(jù),則要使用JSONP。
假設(shè),我要進(jìn)行百度地圖坐標(biāo)轉(zhuǎn)換,這是文檔http://developer.baidu.com/map/changeposition.htm
運(yùn)行示例 http://api.map.baidu.com/geoconv/v1/?coords=114.21892734521,29.575429778924;114.21892734521,29.575429778924&from=1&to=1
瀏覽器打開得到返回值 (注意當(dāng)前返回錯誤,本文只是隨便找個例子用來講解)
{"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函數(shù)
通過<script>標(biāo)簽調(diào)用示例鏈接產(chǎn)生GetValue值時就會彈窗
然后通過火狐firebug進(jìn)入控制臺查看GetValue的參數(shù)傳遞給getVal的值
Object { status=22, message="param error:to illegal, ...support such coord type", result=[0]}