开发者

return data from ajax response

I have this function

function get_last(){
                $.ajax({
                  开发者_如何学C      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 ?


First of all you are calling AJAX asynchrosnously so dont expect you can get the value from ajax response and return it.

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.

If you want you can call ajax sychronously in order to get the response and return it.

    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. In JavaScript, inner functions have access to variables declared in their parent, so last = parseInt(data); will update the variable declared in the parent function.

Also note that you will have to run this synchronously, otherwise the function will return before the response is handled.

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. You need to get rid of that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜