简体   繁体   English

从 ajax 响应返回数据

[英]return data from ajax response

I have this function我有这个 function

function get_last(){
                $.ajax({
                        url:'fronta.php?get_last&last=1',
                        success:function(data) {
                                var last = parseInt(data);

                        }

                });
                return last;

}

but when I call it like但是当我这样称呼它时

var last = get_last();
alert(last);

firebug gives me "last is not defined"萤火虫给了我“最后一个没有定义”

How can I pass this last variable into global scope?如何将最后一个变量传递给全局 scope?

First of all you are calling AJAX asynchrosnously so dont expect you can get the value from ajax response and return it.首先,您异步调用 AJAX 所以不要指望您可以从 ajax 响应中获取值并返回它。

Second thing is var last is defined in success handler's scope so in order to access any variable it should be defined in a proper scope.第二件事是 var last 在成功处理程序的 scope 中定义,因此为了访问任何变量,它应该在适当的 scope 中定义。

If you want you can call ajax sychronously in order to get the response and return it.如果您愿意,您可以同步调用 ajax 以获得响应并返回它。

    function get_last(){
var last = null;
                    $.ajax({
                            url:'fronta.php?get_last&last=1',.
                            success:function(data) {
                                    last = parseInt(data);

                            },
                            async: false

                    });
                    return last;

}
function get_last(){
    var last;
    $.ajax({
        url:'fronta.php?get_last&last=1',
        async: false,
        success:function(data) {
            last = parseInt(data);
        }
    });
    return last;
}

Move the declaration of the last variable to the parent function, instead of having it in the callback.last变量的声明移动到父 function,而不是在回调中。 In JavaScript, inner functions have access to variables declared in their parent, so last = parseInt(data);在 JavaScript 中,内部函数可以访问在其父级中声明的变量,因此last = parseInt(data); will update the variable declared in the parent function.将更新在父 function 中声明的变量。

Also note that you will have to run this synchronously, otherwise the function will return before the response is handled.另请注意,您必须同步运行此操作,否则 function 将在响应处理之前返回。

Also, it may have been a typo when you wrote the question, but there's a random .此外,您写问题时可能是错字,但有一个随机的. character at the end of your url:'fronta... line. url:'fronta...行末尾的字符。 You need to get rid of that.你需要摆脱它。

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

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