为什么JavaScript不能识别PHP的输出?

时间:2014-01-21 16:27:50

标签: javascript php jquery

我让jQuery在PHP上发帖,如下:

$.post("/contact/edit_contact", serialized).done(
    function(response) {
        if (response.success) {
            $('#row-' + id).html(response.html); 
        } else {
            alert("There was a problem saving");
        }

处理它的PHP返回此响应(在网络选项卡中):

<div> 
    A bunch of HTML...
</div>

Warning: Cannot modify header information - headers already sent by (output started at /.../contact.controller.php:56) in /.../include/App.class.php on line 82

Call Stack:
    0.0005     683376   1. {main}() pathTo/index.php:0
    ....       
     pathTo/contact.controller.php:58
    0.6205    6286496   6. header() pathTo/App.class.php:82

{"success":true,"html":"<div>\n .... </div>"} 

但是当我做console.log(response.success)时,我得到“未定义”。

为什么JavaScript / jQuery承诺不会看到response.success设置为true?

2 个答案:

答案 0 :(得分:6)

因为在JSON格式的字符串之前有很多东西。

为什么在JSON字符串之前输出HTML(并尝试修改标题)?

答案 1 :(得分:2)

这里有两件事很重要;首先,输出的代码必须包含您想要返回的JSON。如果删除之前输出的HTML,您很可能也会解决返回的PHP错误。

当你从服务器返回时只有这个......

{"success":true,"html":"<div>\n .... </div>"}

...你必须把它解释为JSON。这样做的最好方法是通过PHP发送标题:

header("Content-Type: application/json; charset=utf-8");

但无论如何,你可以告诉jQuery将响应解释为JSON,无论你在done中添加以下行 - 函数:

response = $.parseJSON(response);

希望这有帮助!