进行嵌套的ajax调用

时间:2018-03-26 06:34:30

标签: javascript json ajax

我正在尝试使用vanilla JS进行HN克隆。

JS CODE:

var apiResult = document.getElementById("apiResult");

function apiContent() {
var url_end = ' https://hacker-news.firebaseio.com/v0/topstories.json? 
print=pretty';
var apiCall = new XMLHttpRequest();
var links = [];

apiCall.onload = function() {
    if(this.status == 200) {
        var apiData = JSON.parse(apiCall.responseText);

        for( var i = 0; i < apiData.length; i++){

            var url = 'https://hacker-news.firebaseio.com/v0/item/' ;
            var c_url = apiData[i] + '.json?print=pretty';
            var final_url = url + c_url;
            links.push(final_url);
        }
            // console.log(links);

            for(var j = 0; j < links.length; j++) {
                var a = links[j];
                var secondRequest = new XMLHttpRequest();
                secondRequest.onload =  function() {
                var secondData = JSON.parse(secondRequest.responseText);
                console.log(secondData);
            }
            secondRequest.open('GET', a, true);
            secondRequest.send();
            }       
    }
    else {
        console.log('Unable to fetch data');
    }
}
apiCall.open("GET", url_end, true);
apiCall.send();


}

第一个api调用'url_end'给出前500个故事的ID,它只返回ID而没有别的。因此,要获取与故事ID相对应的内容,我正在进行另一个AJAX调用,但这次使用ID更新了URL,但它无效。

如何使这项工作?

1 个答案:

答案 0 :(得分:0)

我创建了示例示例。你需要一个闭包来调用循环中的多个ajax。在http://jsonstore.online文档上托管的示例JSON:http://jsonstore.online/#!/documentation

工作JS代码:

var apiResult = document.getElementById("apiResult");
function apiContent() {
var url_end = 'https://api.jsonstore.online/api/PsrWFAEwRVWXXU9y/cities';
var apiCall = new XMLHttpRequest();
var links = [];
apiCall.onload = function() {
    if(this.status == 200) {
        var apiData = JSON.parse(apiCall.responseText);
        for( var i = 0; i < apiData.length; i++){
            var final_url = 'https://api.jsonstore.online/api/PsrWFAEwRVWXXU9y/cities?id='+apiData[i].id ;
            links.push(final_url);
        }
        console.log(links); // Print Link Array
        
        for(var j = 0; j < links.length; j++) {
        	(function(a){
              let secondRequest = new XMLHttpRequest();
              secondRequest.onload =  function() {
                let secondData = JSON.parse(secondRequest.responseText);
                console.log(secondData);
              }
              secondRequest.open('GET', a, true);
              secondRequest.send();
           })(links[j]);
        } 
        
    }
    else {
        console.log('Unable to fetch data');
    }
}
apiCall.open("GET", url_end, true);
apiCall.send();
}
apiContent();