-1
$.post("../js.php", {state: state},
                            function(data) {
                                return data;
                        });

这是我的jQuery代码。就像你可以看到它向 js.php 发送一个 post 请求。

这是 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);

还是行不通。:(

4

5 回答 5

2

帖子中的函数是一个回调函数,你不能从它返回任何东西,因为没有人可以返回它。

您需要使用回调中返回的数据,例如:

$.post("../js.php", {state: state},
                            function(data) {
                                $('.someClass').html(data);
                        });
于 2012-08-06T14:03:37.683 回答
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

If you need to work with the data returned by the async call, do so in the callback.

于 2012-08-06T14:06:27.173 回答
0
var data = null;
$(...).click(function(e) {
    $.post("../js.php", {state: state},
                        function(response) {
                            data = response;
                    });
});

之后只需访问data变量。请记住,除非发布请求完成,否则它的值将为空。

于 2012-08-06T14:02:41.910 回答
0

您发布的示例每次都不会执行任何操作,因为这样的 AJAX 调用是异步的(这就是 AJAX 中的A所代表的意思)。

如果您希望能够使用输出的值,请使用包含该值的唯一 ID 向您的页面添加一个隐藏元素。然后您可以通过 javascript 访问该元素。

于 2012-08-06T14:03:11.967 回答
0

那是因为,ajax 调用是异步的。您永远不应该从回调函数返回值。在回调中完成工作或触发事件。

于 2012-08-06T14:03:44.197 回答