Php 返回post数据

Php 返回post数据,php,javascript,jquery,Php,Javascript,Jquery,这是我的jquery代码。如您所见,它向js.php发送post请求 下面是js.php的代码 $.post("../js.php", {state: state}, function(data) { return data; }); 现在,当我提醒js文件中的“数据”时,它会显示良好。但当试图返回它或将它分配给变量时,它不起作

这是我的jquery代码。如您所见,它向js.php发送post请求

下面是js.php的代码

$.post("../js.php", {state: state},
                            function(data) {
                                return data;
                        });
现在,当我提醒js文件中的“数据”时,它会显示良好。但当试图返回它或将它分配给变量时,它不起作用。控制台告诉我,分配了数据值的变量未定义

有什么想法吗

更新代码:

{...}
$query = "SELECT * FROM table WHERE x='" . $y . "'";

$result = $mysqli->query($query);

$num_rows = $result->num_rows;

echo $num_rows ? $num_rows : 0;
仍然不工作(


在此之后,只需访问
数据
变量。请记住,除非post请求完成,否则其值将为null。

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


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

帖子中的函数是回调函数,您无法从中返回任何内容,因为没有人可以将其返回

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

var data = null;
$(...).click(function(e) {
    $.post("../js.php", {state: state},
                        function(response) {
                            data = response;
                    });
});

这是因为,ajax调用是异步的。您永远不应该从回调函数返回值。在回调函数中执行作业或触发事件。

传递给异步方法(如
$)的回调将在将来某个时间执行,一旦异步调用返回。JavaScript执行将继续并继续现在位于其他地方,因此没有任何地方可供回调
返回

想象一下:

$.post("../js.php", {state: state},
                            function(data) {
                                $('.someClass').html(data);
                        });

如果需要处理异步调用返回的数据,请在回调中执行。

返回数据;
在成功回调中不起任何作用。您必须处理后台脚本的输出。您必须了解AJAX是异步的,这就是为什么更新的代码也无法工作的原因。响应数据只是av可以从
complete
回调中找到。为什么要在我的post函数中添加一个click函数?另外,还添加了我自己编写的版本。但它不起作用。:/var data=null;$.post(../js.php),{state:state},function(response){data=response;});console.log(data);我刚才提到了它作为一个例子。这里的要点是在您的post代码之前定义日期,并在收到响应时设置其值。请记住,除非post请求完成,否则其值将为null。感谢您提供的信息,这很有帮助。
$.post("../js.php", {state: state},
                            function(data) {
                                $('.someClass').html(data);
                        });
//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