[英]JSON call inside JSON response.
我在另一個調用中有一個JSON API調用。 這是因為loadJSON()需要第一次調用的動態數據(lat / lon值)。
由於數據是異步的,因此它似乎無法及時工作 - 因此控制台會在控制台的末尾輸出站名。
但是正確的站名不會注入正確的站ID(例如站-4)。
任何幫助非常感謝。 請注意,我理想地尋找一種不依賴於jQuery的解決方案。
window.apiCallback = function(data) {
for (i=0; i < 10; i++) {
document.getElementById("title-"+i+"").innerHTML = data.results[i].name;
}
loadJSON('http://trainstationsdata/near.json?lat='+data.results[i].venue.lat+'&lon='+data.results[i].venue.lon+'&page=1&rpp=1',
function(result) {
// this works and outputs at the end of console
console.log(result.stations[0].name);
// this doesn't work
document.getElementById("station-"+i+"").innerHTML = result.[i].station_name;;
},
function(xhr) { console.error(xhr); }
);
}
function loadJSON(path, success, error)
{
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
if (success)
success(JSON.parse(xhr.responseText));
} else {
if (error)
error(xhr);
}
}
};
xhr.open("GET", path, true);
xhr.send();
}
您可以嘗試成功,或完成ajax方法,該方法在請求完成時運行(在成功和錯誤函數之后)。
像這樣的東西。
function testAjax(handleData) {
$.ajax({
url:"getvalue.php",
complete:function(data) {
handleData(data);
}
});
}
沒有JQuery的解決方案就是這樣的。
var r = new XMLHttpRequest();
r.open("POST", "webservice", true);
r.onreadystatechange = function () {
if (r.readyState != 4 || r.status != 200) return;
console.log(r.responseText);
};
r.send("a=1&b=2&c=3");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.