$.post("../js.php", {state: state},
function(data) {
return data;
});
这是我的jquery代码。就像你可以看到它向js.php发送一个帖子请求。
这是js.php的代码。
{...}
$query = "SELECT * FROM table WHERE x='" . $y . "'";
$result = $mysqli->query($query);
$num_rows = $result->num_rows;
echo $num_rows ? $num_rows : 0;
现在,当我在js文件中提醒“数据”时,它显示正常。但是当试图返回它或将它分配给变量时它不起作用。控制台告诉我,已经分配了数据值的变量是未定义的。
有什么想法吗?
更新的代码:
var data = null;
$.post("../js.php", {state: state},
function(response) {
data = response;
});
console.log(data);
仍然无法正常工作。 :(
答案 0 :(得分:2)
帖子中的函数是一个回调函数,你不能从中返回任何东西,因为没有人将它返回。
您需要使用回调内部重新记录的数据,例如:
$.post("../js.php", {state: state},
function(data) {
$('.someClass').html(data);
});
答案 1 :(得分:1)
一旦异步调用返回,您传递给异步方法(如$.post
)的回调将在未来的某个时间执行。 JavaScript执行已经移动,现在已经移到其他地方,因此您无法回调return
到。
想象一下:
//Some code... executed as you would expect
var data; //Currently undefined
$.post("../js.php", {state: state}, function(response) {
//Callback is executed later, once server responds
data = response; //No good, since we already executed the following code
return response; //Return to where? We have already executed the following code
});
/* More code... we carry on to this point straight away. We don't wait for
the callback to be executed. That happens asynchronously some time in
the future */
console.log(data); //Still undefined, callback hasn't been executed yet
如果您需要处理异步调用返回的数据,请在回调中执行此操作。
答案 2 :(得分:0)
var data = null;
$(...).click(function(e) {
$.post("../js.php", {state: state},
function(response) {
data = response;
});
});
之后只需访问data
变量。请记住,除非发布请求,否则其值将为null。
答案 3 :(得分:0)
您发布的示例每次都不会执行任何操作,因为这样的AJAX调用是异步的(这就是AJAX中 A 所代表的意思)。
如果您希望能够使用输出的值,请使用包含该值的唯一ID向页面添加隐藏元素。然后你可以通过javascript访问该元素。
答案 4 :(得分:0)
那是因为,ajax调用是异步的。您永远不应该从回调函数返回值。在回调中完成工作或触发事件。