开发者

How do you return the data from an AJAX success event to the outer function?

I want the ch开发者_高级运维eck_membership() function below to return the AJAX "data". However, "result" keeps getting set to the XHR object, not the returned JSON object.

How do I fix this?

function check_membership() {

    var result;

    result = jQuery.ajax({
        type: 'POST',
        url: '/ajax/member',
        dataType: 'json',
        async: false,
        success: function(data) {
            return data;
        }
    });

    return result;

}

Thanks.


Javascript will not 'wait' for the $.ajax's success callback to fire before returning from the main function, so there's a good chance that nothing will be returned. You will have to either use a synchronous-Jax call by setting the async option to false (which will block the browser for the duration of the request) or revise your strategy, e.g. by doing what you want to ultimately get done within the success callback. For example:

function update_membership_status() {
    jQuery.ajax({
        type: 'POST',
        url: '/ajax/member',
        dataType: 'json',
        success: function(json) {
            $("#status").text('Signed In:' + json.SignedIn + "  msg" + json.msg);
        }
    });
}


var result = 
{
   ajax: function(){
        jQuery.ajax({
        type: 'POST',
        url: '/ajax/member',
        dataType: 'json',
        async: false,
        success: function(data) {
                return data.signedIn;
        }
     });
   }  
}

then call result.ajax(); by whatever


You can use async property to return data synchronously:

function check_membership() {
  var result = jQuery.ajax({
        type: 'POST',
        url: '/ajax/member',
        dataType: 'json',
        async: false
    });
 return result.SignedIn;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜