PHP函数没有向JQuery ajax方法返回任何数据

我正在使用jquery的ajax方法将一些数据发布到服务器并获取响应。 虽然服务器端php代码返回一个json编码的字符串/数组,但响应将返回null。

有人可以指出我正在犯的错误。 下面如果我的jquery ajax方法使用哪个我正在点击postData.php页面。

$.ajax({ url:'postData.php', type:'POST', data:data, dataType: "json", success: function(response){ console.log(response); } }); 

postData.php中的内容非常简单,因为我还在开发它。

  $data = array(); //inside postData.php $data['test']=1; return json_encode($data); 

它应该返回一个json字符串,但它返回null。 我也尝试在$ data数组声明之后回显一个字符串,它确实在firebug中回显它,但响应是当我在成功回调上执行console.log时,它返回为null。

这就是postData.php中的所有内容吗? 您需要在某个时刻将其写入缓冲区(echo json_encode($ data);)。

要将结果返回到ajax函数中,必须回显它,而不是返回,如:

 $data = array(); $data['test']=1; echo json_encode($data); 

像morgar指出的那样,你应该回显数据而不是使用return。

 $data = array(); $data['test']=1; echo json_encode($data); //echo instead of return 

同时,在成功函数的ajax中,您应该像数组一样访问响应。

 **Incorrect** console.log(response); //--> would return an error **Should Be** console.log(response[0]); //--> read the returned first array element