开发者

Let the $.post function return the response in the parent function

开发者 https://www.devze.com 2023-01-24 16:16 出处:网络
I got this code: function server_request(module,section,action,data) { data[\'module\'] = module; data[\'section\'] = section;

I got this code:

function server_request(module,section,action,data) {
    data['module'] = module;
    data['section'] = section;
    data['action'] = action;
    var responsetxt = null;
    $.post('../application/server.php', data, function(data) {
        responset开发者_如何转开发xt = data;
    });
    return responsetxt;
}

And it return's null ?

What i want is let the server_request function return the responseText? But at some way it doesn't work, why? And how to let it work?


You're providing a callback function to $.post, which will be run when the request is returned. The server_request function returns immediately (i.e. before the response is available) so responsetxt will still be null.

To get around this you could add a callback parameter to server_request, then execute it in the anonymous function you provide to the $.post call:

function server_request(module,section,action,data,callback) {
    data['module'] = module;
    data['section'] = section;
    data['action'] = action;
    $.post('../application/server.php', data, function(data) {
        callback(data);
    });
}

You could then use this like:

$(function() {
    var module = x, section = y, data = z;
    server_request(module, section, data, function(response) {
        $('#result').html(response); // do stuff with your response
    });
});

Check out continuation passing style for more information ( http://en.wikipedia.org/wiki/Continuation-passing_style and http://matt.might.net/articles/by-example-continuation-passing-style/).


You could get the return value, but only when doing a synchronous call instead of an asynchronous one:

function server_request(module,section,action,data,callback) {
    data['module'] = module;
    data['section'] = section;
    data['action'] = action;
    responsetxt = $.ajax({
       "url": '../application/server.php', 
       "async": false,
       "type": "POST",
       "data": data
       }).responseText;
    return responsetxt;

}

Remember that a synchronous call like this freezes the browser until the server responds.

0

精彩评论

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