我正在尝试从我的 ajax 调用中获取一个变量:
$.ajax({
type: "POST",
url: "insert",
data: { title:title, start:dstart, end:dend },
contentType: "application/json",
dataType : 'json',
success : function(data) {
data = JSON.parse(data);
console.log('data = '); // is showing the data with double quotes
console.log(data);
}
});
还有我的 PHP:
$id = $calendar->getId();
$json = array ( 'id' => $id );
var_dump(json_encode($json));
json_encode($json);
通过我的 var_dump
,我可以看到我的 json_encore
,例如:
string '{"id":156}' (length=10)
但在我的 ajax()
成功中,console.log()
没有在我的控制台中显示任何内容。
我在哪里可以查看我的 success: function(data)
是否为空?我只会在我的 ajax 成功中捕捉到 id。
更新:问题已解决。事实上,我正在使用 symfony,而且我还没有在我的操作中看到我的 PHP 在哪里,symfony 调用的页面(indexSuccess.php)不是空的,这就是它根本不起作用的原因。)
最佳答案
如果您看一下您的 PHP 代码,您基本上对 json_encode() 的输出什么都不做 ...
请将您的 PHP 代码的最后一行更新为:
echo json_encode($json);
现在你应该得到你想要的数据作为响应。
编辑:@1nsan3,你在评论中问 echo 是否与 var_dump() 不一样......我想你在这里得到了答案:What's the difference between echo, print, and print_r in PHP?
编辑2:
请删除 JSON.parse() 调用。使用 dataType : 'json'
时,jQuery 已经解析了 AJAX 请求的响应,
如 http://api.jquery.com/jQuery.ajax 中所述
关于php - 带有返回 json 的 ajax 调用永远不会成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16708581/