带有返回json的Ajax调用永远不会成功

ajax call with a return json never catch in success

本文关键字:永远 成功 调用 Ajax 返回 json      更新时间:2023-09-26

我试图从我的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()相同…我想你在这里得到了答案:PHP中echo、print和print_r之间的区别是什么?

EDIT2:

请删除JSON.parse()调用你的AJAX请求的响应已经被jQuery解析时,使用dataType : 'json',如http://api.jquery.com/jQuery.ajax

所述

你确定php返回的是有效的json数据吗?

php

$id = $calendar->getId();
$json = array('id' => $id);
echo json_encode($json);         <-- your php code must echo only this valid json, 
return;                              make sure no other values are echoed 
                                     above or below this which will break json.

js

success : function(data) {
  if($.trim(data) != '') {
    console.log(data);
  } else {
    console.log('no data');
  }
}