开发者

how to return response from post in a variable? jQuery

edited: This is what i need:

sendpost = function(a,b,c){
    return jQuery.post('inc/operations.php', {a:b}, c, "json");
},

rotate = function(callback){
    //....
    alert(callback);
}

sendpost('operation', 'test', rotate)

old post: i use this function to return the response of post:

$.sendpost = function(){
    return jQuery.post('inc/operations.php', {'operation':'test'}, "json");
},

i want to make something like this:

in:

$.another = function(){
  var sendpost = $.sendpost();
  alert(sendpost);
}

but i get: [object XMLHttpRequest]

if i print the object with:

jQuery.each(sendpost, function(i, val) {
  $(".displaydetails").append(i + " => " + val + "<br/>");
});

i get:

details  abort => function () { x && h.call(x); g("abort"); }
dispatchEvent => function dispatchEvent() { [native code] }
removeEventListener => function removeEventListener() { [native code] }
open => function open() { [native code] }
setRequestHeader => function setRequestHeader() { [native code] }
onreadystatechange => [xpconnect wrapped nsIDOMEventListener]
send => function send() { [native code] }
readyState => 4
status => 200
getResponseHeader => funct开发者_C百科ion getResponseHeader() { [native code] }
responseText => mdaaa from php

how to return only the response in the variable?


This is not possible.

AJAX calls are asynchronous, meaning that your code continues running before the server sends a reply.

When the return statement executes, there is no reply from the server yet.

It is possible to make a synchronous AJAX call, but it will completely freeze the browser and should be avoided at all costs.

Instead, you should make your function take a callback that will receive the server's response, and call that callback from $.post's callback. (This is how jQuery's AJAX functions return values)

EDIT: For example:

$.sendpost = function(callback) {
    return jQuery.post('inc/operations.php', {'operation':'test'}, callback, "json");
};

$.another = function() { 
    $.sendpost(function(response) {
        alert(response);
    });
};
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜