仅在ajax调用完成后才在函数中返回值? [英] Returning value in function only when ajax call has completed?

查看:111
本文介绍了仅在ajax调用完成后才在函数中返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在使用mootools,并且我有一个函数调用ajax脚本来获取值.然后,该值将在函数中返回.但是,由于某些原因,该函数对于AJAX调用返回的速度太快了!

So I am using mootools, and I have a function that calls an ajax script to get a value. This value is then returned in the function. However, for some reason, the function returns too quickly for the AJAX call!

我在做什么错...

function getCredits() {
    var loadGlobalTab = new Request.JSON({
        url: {my api, url removed for security},
        evalScripts : true,
        async: false,    // I tried this, hoping it would stop the function from returning too soon, but no dice.
        onSuccess: function(returnInfo) {
            alert(returnInfo.data.total);
            return returnInfo.data.total;
        }
    }).send(sendData);    // Where sendData has been defined prior
}

警报返回正确的值,因此我知道AJAX调用有效,但是该函数本身不返回任何值,这意味着在进行AJAX调用时,该函数立即结束.

The alert returns the proper value, so I know the AJAX call works, however, the function itself returns nothing, meaning that while the AJAX call is being made, the function ends right away.

我尝试将return 100放在最后,仅用于踢球,然后该函数返回100.

I tried putting a return 100 at the end, just for kicks, and the function returned 100.

推荐答案

ajax是asynchronous

意思是JS会正确读取它,如果没有返回,那么就什么也没有.

Meaning that JS will read right through it and if there is no return right then, then there is nothing.

要做的一件好事是回调而不是返回:

The good thing to do is a callback instead of a return:

function getCredits() {
    var loadGlobalTab = new Request.JSON({
        url: {my api, url removed for security},
        evalScripts : true,
        headers: {'ACCEPT': 'json','X_REQUESTED_WITH':'jsonhttprequest'},
        onSuccess: function(returnInfo) {
            alert(returnInfo.data.total);
            //goto callback
            getCredits_Callback(returnInfo.data.total);
        }
    }).send(sendData);    // Where sendData has been defined prior
}

function getCredits_Callback(total){
   //do something with total
}

第二种方法:

function getCredits() {
    var loadGlobalTab = new Request.JSON({
        url: {my api, url removed for security},
        evalScripts : true,
        headers: {'ACCEPT': 'json','X_REQUESTED_WITH':'jsonhttprequest'},
        onSuccess: getCredits_Callback
    }).send(sendData);    // Where sendData has been defined prior
}

function getCredits_Callback(returnInfo){
   //do something with returnInfo
}

这篇关于仅在ajax调用完成后才在函数中返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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