作者: , 出處:Dev2Dev, 責(zé)任編輯: 葉江,
2007-06-13 14:59
本文中將使用工具輕松構(gòu)建終極的Hello World mashup:Google地圖mashup……
客戶端將使用XMLHttpRequest 從REST服務(wù)檢索JSON 對象。一旦檢索到該對象,JavaScript 代碼將需要反序列化對象,然后遍歷整個數(shù)組。看一下mapper.js,就可以看到 getLocationsAndMap 和 getLocationsAndMapCallback 函數(shù)完成了這一功能:
// Gets the current locations from the REST service // on the server and writes out the HTML that // contains links for the map function getLocationsAndMap() { if (receiveReq.readyState == 4 || receiveReq.readyState == 0) { // getD2DSites.html is a REST service // that returns the list of locations // as JSON receiveReq.open("GET", ‘getD2DSites.html‘, true); receiveReq.onreadystatechange = getLocationsAndMapCallback; receiveReq.send(null); } // end if } // end function function getLocationsAndMapCallback() { // state == 4 is when the response is complete if (receiveReq.readyState == 4) { // Deserialize the JSON response (eval() command) // This creates an array of location objects. var response = eval("("+request.responseText+")"); // generate HTML listing the locations and update // the page DOM so the user will see the HTML var div = document.getElementById(‘loc_div‘); div.innerHTML = ‘<p>Received ‘ + response.locations.location.length+‘ results.‘; for(i=0;i < response.locations.location.length; i++) { var city = response.locations.location[i].city; var anchor = ‘‘; // TODO: we will fix this later div.innerHTML += ‘<p><b>‘+ city + ‘</b> ‘ + anchor + loc + ‘</a><br/>‘ + addr + ‘</p>‘; } // end for loop } // end if (state == 4) } // end function |
請注意, eval 調(diào)用將接收J(rèn)SON 并對它進(jìn)行計算,有效地構(gòu)建一個可以導(dǎo)航的JavaScript數(shù)組。For 循環(huán)顯示了如何在數(shù)組內(nèi)遍歷地理位置:
至此,您已經(jīng)完成了這些工作:
- 創(chuàng)建一個靜態(tài)的 REST 服務(wù) HTML 文件
- 向HTML文件添加一個JSON 有效負(fù)載
- 編寫代碼通過eval()將JSON 重構(gòu)為一個JavaScript 對象
- 編寫代碼來循環(huán)遍歷地址數(shù)組,使用新的HTML操縱DOM
現(xiàn)在,讓我們來看如何在Google 地圖中顯示這些位置。