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。
I am using jquery's ajax method to post some data to the server and get back the response. Though the server side php code is returning a json encoded string/array, the response is coming back as null.
Could someone point out the mistake that I am making. Below if my jquery ajax method using which I am hitting the postData.php page.
$.ajax({
url:'postData.php',
type:'POST',
data:data,
dataType: "json",
success: function(response){
console.log(response);
}
});
The content in postData.php is pretty straight forward as I am still developing it.
$data = array();
//inside postData.php
$data['test']=1;
return json_encode($data);
It should return a json string, but it is returning null. I also tried echoing a string just after $data array declaration, it does echo it in the firebug, but the response is when I do a console.log on the success callback, it comes back as null.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为了将结果返回到 ajax 函数中,您必须 echo 它,而不是 return,例如:
For getting the result back in your ajax function, you must echo it, not return, like:
这就是 postData.php 中的全部内容吗?您需要在某个时候将其写到缓冲区(echo json_encode($data);)。
Is that all that is in postData.php? You need to write it out to the buffer (echo json_encode($data);) at some point.
正如 morgar 指出的那样,您应该回显数据而不是使用 return。
同时,在 ajax on success 函数中,您应该像访问数组一样访问响应。
Like morgar pointed it out, you should echo the data back and not use return.
At the same time, in your ajax on success function, you should access the response like an array.