首页 > 解决方案 > JSON 输出未显示在控制台日志中

问题描述

我正在尝试为我的博客的非活动文章创建一个通知按钮,我不希望管理员重新加载他/她的页面以查看提交的新非活动文章,所以我想使用 Ajax 执行此操作,但是,我很新到阿贾克斯。我已经从数据库中获取数据,并以名为 file.php 的文件名存储在 JSON 中,这是我的代码:

require $_SERVER['DOCUMENT_ROOT'].'/config/init.php';

require CLASS_PATH.'article.php';

$article = new Article();

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

$list = $article->getInactiveArticle();

echo json_encode($list);

我为 Ajax 编写了以下代码行:

    <script>
    $.ajax({
    type: "POST",
    url: 'file.php',
    dataType: 'json',
    success: function(response)
    {
        if (response != 0 ) {
            if (typeof(response) != "object") {
                response = $.parseJSON(response);
                console.log(response);
            }
        }
    }
});
</script>

尽管 JSON 中有数据,但我在控制台中没有得到任何东西。应该做什么?

标签: javascriptphpjqueryajax

解决方案


尽管 JSON 中有数据,但我在控制台中没有得到任何东西。

where$.ajax() type设置为"json"第一个参数 atcallback是一个 JavaScript 普通对象,而不是JSON字符串。

应该做什么?

删除if语句并使用console.log(response). JSON.parse()没有必要。

$.ajax({
  type: "POST",
  url: 'file.php',
  dataType: 'json',
  success: function(response) {
    console.log(response);
  }
})

推荐阅读