csdn产品小助手 2011-07-06 19:28 采纳率: 0%
浏览 40

从ajax响应返回数据

I have this 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 ?

  • 写回答

2条回答 默认 最新

  • weixin_33675507 2011-07-06 19:30
    关注
    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.

    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料