weixin_33686714 2014-05-01 17:29 采纳率: 0%
浏览 35

$ .ajax调用后返回

I've this piece of code, and i built the other function only to try another way to do that.

var cookie_val = "";
    function getCookie() {        
        $.when($.ajax("../handlers/users/get_user.ashx")).then(function (data, textStatus, jqXHR) {
            $.when(getCookieValue(data)).then(function () {
                cookie_val = $.cookie("default_value:" + cookie_val);
            });            
        });
        return cookie_val;
    }
    function getCookieValue(data) {
        cookie_val = data;
    }

this works, but only if i execute the function twice, how can i do to make this work at the first call?

  • 写回答

1条回答 默认 最新

  • csdnceshi62 2014-05-01 17:43
    关注

    You have to wait for the ajax request to finish before grabbing the value: https://api.jquery.com/jQuery.when/ . The requests made in getCookie are both asynchronous, so they don't halt other code from executing while they are waiting for a response from the server. There's two ways you can get around this:

    Return the deferred object created in getCookie

    function getCookie() {
        return $.when(....
    }
    

    And when it's done, do what you need with the cookie value

    getCookie().done(function (cookie_value) {
        console.log(cookie_value);
    });  
    

    Alternatively, make the call synchronous: https://api.jquery.com/jQuery.ajax/

    function getCookie() {
        $.ajax({
            url: '../hnadlers/users/get_user.ashx', 
            async: false
        }).done(function (data, textStatus, jqXHR) {
            cookie_value = $.cookie('default_value:' + data);
        });
        return getCookieValue();
    }
    

    Also, are you sure getCookieValue shouldn't return cookie_val, as your current implementation suggests, it should be named setCookieValue.

    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!