编辑: 这就是我需要的:
sendpost = function(a,b,c){
return jQuery.post('inc/operations.php', {a:b}, c, "json");
},
rotate = function(callback){
//....
alert(callback);
}
sendpost('operation', 'test', rotate)
旧帖: 我使用此函数返回帖子的响应:
$.sendpost = function(){
return jQuery.post('inc/operations.php', {'operation':'test'}, "json");
},
我想做这样的事情:
在:
$.another = function(){
var sendpost = $.sendpost();
alert(sendpost);
}
但我得到:[object XMLHttpRequest]
如果我打印对象:
jQuery.each(sendpost, function(i, val) {
$(".displaydetails").append(i + " => " + val + "<br/>");
});
我得到:
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 => function getResponseHeader() { [native code] }
responseText => mdaaa from php
如何只返回变量中的响应?
最佳答案
这是不可能的。
AJAX 调用是异步的,这意味着您的代码会在服务器发送回复之前继续运行。
return
语句执行时,服务器还没有回复。
可以进行同步 AJAX 调用,但它会完全卡住浏览器,应不惜一切代价避免。
相反,您应该让您的函数接受一个将接收服务器响应的回调,并从 $.post
的回调中调用该回调。 (这就是 jQuery 的 AJAX 函数返回值的方式)
编辑:例如:
$.sendpost = function(callback) {
return jQuery.post('inc/operations.php', {'operation':'test'}, callback, "json");
};
$.another = function() {
$.sendpost(function(response) {
alert(response);
});
};
关于php - 如何从变量中的帖子返回响应?查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2708589/