【问题标题】:What's wrong with this json response?这个 json 响应有什么问题?
【发布时间】:2018-02-23 08:06:49
【问题描述】:

我已将接受的答案复制到问题How do I return a proper success/error message for JQuery .ajax() using PHP?

我的 PHP 脚本返回以下 json。标题正确:PHP 脚本输出中的Content-type: application/jsonjson_encode()

{"success":"success"}

但是用于检查状态的 jquery 不起作用:

$.ajax({
        type: "POST",
        url: '/ajax/index',
        data: $("#NewsletterSignup").serialize(), 
        success: function(data)
        {
            console.log(data);
            if (data.success == 'success') {
                console.log('successful');
            } else if(data.errors){
                console.log('error occurred');
            }
        }
    });

所以我得到了初始的console.log(data),它给出了{"success":"success"}。但是它没有评估if...else if 条件。为什么?

jquery 版本是 1.12.3

【问题讨论】:

  • 你没有在你的ajax代码中指定dataType:"JSON"
  • 谢谢,已经解决了。
  • 或将header('Content-type: application/json;charset=UTF-8'); 添加到您的PHP 文件中
  • @DarkBee 已经在那里了。问题在于我的 js 中缺少 dataType
  • 那你做错了,Jquery.ajax 能够猜出正确的数据类型

标签: jquery json ajax


【解决方案1】:

像这样将 dataType 添加到您的 ajax 代码中:

$.ajax({
    type: "POST",
    url: '/ajax/index',
    data: $("#NewsletterSignup").serialize(), 
    dataType:'json,'    //  CHECK THIS....
    success: function(data)
    {
        console.log(data);
        if (data.success == 'success') {
            console.log('successful');
        } else if(data.errors){
            console.log('error occurred');
        }
    }
});

【讨论】:

  • 这就是问题所在。提供响应的 PHP 脚本已经发送了正确的 json 标头。问题是我的 js 中缺少 dataType:
  • 感谢@Andy 接受答案。乐于助人。
【解决方案2】:

那是因为您的 php 服务器以纯文本而不是 json 形式给出响应。查看标题Content-Type: text/html。您的服务器需要将标头作为带有Content-type: application/json 的json 发送。

<?php
  $data = /** whatever you're serializing in array **/;
  header('Content-Type: application/json');
  echo json_encode($data);

或者,如果响应在 plain text 中,您可以在客户端 (javascript) 中将该响应解析为 json。这样做:

$.ajax({
    type: "POST",
    url: '/ajax/index',
    data: $("#NewsletterSignup").serialize(), 
    success: function(data)
    {
        data = JSON.parse(data); 
        console.log(data);
        if (data.success == 'success') {
            console.log('successful');
        } else if(data.errors){
            console.log('error occurred');
        }
    }
});

您还可以使用dataType:'json' 选项在 jquery ajax 中获得 json 响应。

【讨论】:

  • 最好将;charset=UTF-8添加到标题中以指定字符集
【解决方案3】:

你需要从 php 文件中将其编码为

json_encode({"success":"success"});

应该期待dataType:'json'

【讨论】:

    猜你喜欢
    • 2013-08-25
    • 1970-01-01
    • 1970-01-01
    • 2016-10-08
    • 2013-02-24
    • 1970-01-01
    • 1970-01-01
    • 2015-12-04
    相关资源
    最近更新 更多