当async为true时,Ajax Call返回未定义 [英] Ajax Call returns undefined when async is true

查看:130
本文介绍了当async为true时,Ajax Call返回未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具有功能,并且在async为false时可以正常工作,但是我想要相同的功能(我的意思是返回值),但async为true.

have function and it's working when async is false, but I want the same functionality (by which I mean return value) but with async is true .

  function Call(param, proc) {
    var url = "../../DataManager/DataManagment.aspx/DataSelector";
    var ret;
    $.ajax({
        url: url,
        type: "POST",
        datatype: "json",
        data: JSON.stringify({
            "data": param,
            "action": proc
        }),
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            ret = data;
        },
        async: false,
        error: errorFn
    });
    return ret.d;
}

推荐答案

You can't return from asynchronous code like AJAX. Instead you need to reconsider your function a littler.

因此,您要么需要使用回调并在成功函数中调用它,要么更好地只是返回promise对象:

So you either need to use a callback and call it in success function or better just return promise object:

function Call(param, proc) {
    var url = "../../DataManager/DataManagment.aspx/DataSelector";
    return $.ajax({
        url: url,
        type: "POST",
        datatype: "json",
        data: JSON.stringify({
            data: param,
            action: proc
        }),
        contentType: "application/json; charset=utf-8",
        error: errorFn
    });
}

Call(params, process).then(function(data) {
    console.log(data);
});

这篇关于当async为true时,Ajax Call返回未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆