cicle完成后AJAX返回变量

时间:2016-02-26 14:57:14

标签: javascript jquery ajax

我正在尝试计算外部API的结果总和,我需要为每个关键字发出一个请求。代码执行成功但函数在完成所有ajax请求之前返回值。 我试图添加“async”param,但它已被弃用,然后我做了这个:

function calcTotal(arr) {
var t_docs = 0;
var i = 0;
var len = arr.length;
var aReq = []
for(i = 0; i < len; i++)
{
    console.log(i);
    var apiDataLQKT = {
        keyword: arr[i],
        start_date: "2015-01-01",
        end_date: "2015-06-01",
        format: 'jsonp',
        sources_types: sources,
        sources_names: names,
        domains: argDomains,
        words: terms,
        author_id: usrID,
        sentiment:sentiment,
        positive_threshold:posThresh,
        negative_threshold:negThresh,
        language:lang,
        author_location:geolocations,
        author_gender:genderID,
        typologies:typID,
        document_type:docType,
        source_base_url:'',
        emotion:'',
        metadata:'',
        order_sort:'',
        order_by:''
    }
    console.log(apiDataLQKT);
    aReq[i] = $.ajax({
        type:'GET',
        url:apiUrl+'LightQuantitativeKeywordTrend',
        contentType: 'application/javascript',
        crossDomain: true,
        dataType: 'jsonp',
        data: apiDataLQKT,
        success: function(json) {
            var res = json.LightQuantitativeKeywordTrend;
            t_docs += res.count;
            console.log("T_DOCS[" + arr[i] + "]: " + t_docs);
        }
    });
}
aReq[arr.length-1].done(function(data){
    return t_docs;
});
}

控制台日志输出:

Total: 0
T_DOCS[undefined]: 1445
T_DOCS[undefined]: 1521
...

我还能尝试什么?

1 个答案:

答案 0 :(得分:0)

您无法从异步调用返回值,例如AJAX请求,并期望它能够正常工作,因为等待响应的代码已经在收到响应时执行。

解决这个问题的方法是在success:callback中运行必要的代码。 Ω在这种情况下,只有在可用时才访问数据。

相关问题