简体   繁体   English

如何从ajax调用函数返回值

[英]How to return value from an ajax call function

I have a function 我有一个功能

function GetITStaffList(){
    var go_path = "Server/ITComplains.php?action=GetITStaffList&vars=0";
    $jqLibrary.get(go_path,
        {}, function(data)
        {
            var parseData = JSON.parse(data);
            console.log("GetPendingAndInProgressComplainsByGeneratorId : ", parseData);

            return parseData;
        });
}

I am calling this somewhere in the code like this 我在这样的代码中的某个地方称呼它

var ITStaffList = GetITStaffList();
MakeDropDownITStaff(ITStaffList);

But the problem is each time it is returning null. 但是问题是每次它返回null时。 I know that I have to use callback and something like a promise but I don't how to fit this thing in my context. 我知道我必须使用回调和诸如Promise之类的东西,但是我不适合在我的上下文中使用它。 How do I write a reusable function with ajax call that returns data on demand.? 如何编写带有ajax调用的可重用函数,该函数可按需返回数据?

Return a promise instead. 代替诺言。

function GetITStaffList(){

    return new Promise(function(resolve){

       var go_path = "Server/ITComplains.php?action=GetITStaffList&vars=0";
       $jqLibrary.get(go_path,
           {}, function(data)
           {
               var parseData = JSON.parse(data);
               console.log("GetPendingAndInProgressComplainsByGeneratorId : ", parseData);

            resolve(parseData);    //Notice this
        });
    })
}

Now you can call the function and wait for data. 现在您可以调用该函数并等待数据。

GetITStaffList().then(function(data){
    console.log(data)
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM