php - jQuery AJAX 无法使用 JSON 响应

标签 php jquery ajax json

我的 php 文件有一个 JSON 响应,例如:

[
  {"id":"1"},
  {"archiveitem":"<small>26.06.2015 12:25<\/small><br \/><span class=\"label label-default\">Bug<\/span> has been submitted by Admin"}
]

并尝试在单击按钮后将此响应提取到一个 div 中,但是 Firebug 告诉我来自错误处理程序的消息。我无法弄清楚问题所在?

$('#loadarchive').click(function(){
    $.ajax({
        type: 'post',
        url: '/src/php/LoadAdminDashboardArchive.php',
        dataType: 'json',
        data: {
            action : 'getArchive'
        },
        success: function(results) {
            var archiveelements = JSON.parse(results);
            console.log(results);
            $.each(archiveelements, function(){
                $('#archivecontent').html('<div class="mark-read-container"><span class="btn-mark-unread" id="' + this.id + '">Unarchive</span></div><div class="bs-callout bs-callout-default">' + this.archiveitem + '</div>');
            });
        },
        error: function(){
            console.log('Cannot retrieve data.');
        }
    });
});

最佳答案

我试着运行你的代码,我得到了

SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data

通过定义 dataType: 'json' 您的结果已经被解析为一个数组。所以你可以这样做:

success: function (results) {
    if (results["head"]["foo"] != 0) {
        // do something
    } else if (results["head"]["bar"] == 1) {
        // do something
    }
}

这适用于我的电脑:

$.ajax({
    type: 'post',
    url: '/src/php/LoadAdminDashboardArchive.php',
    dataType: 'json',
    data: { action : 'getArchive' },
    success: function(results) {
        console.log(results);
        $.each(results, function(){
            $('#archivecontent').html('<div class="mark-read-container"><span class="btn-mark-unread" id="' + this.id + '">Unarchive</span></div><div class="bs-callout bs-callout-default">' + this.archiveitem + '</div>');
        });
    },
    error: function(){
        console.log('Cannot retrieve data.');
    }
});

关于php - jQuery AJAX 无法使用 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31378271/

相关文章:

jquery - spring MVC 3 get请求从ie错误地返回代码304

php - jQuery 插件无法在加载了 ajax 的页面上运行

php - 通过套接字发送数据的过程到底是如何工作的?

php - 当我尝试使用 PHP 对 .js 文件进行 GZIP 压缩时,出现了某种与 PHP 相关的错误

php - 如何在没有 exec() 函数的情况下从 mysql 导出数据库

jQuery .nextAll 不起作用?

php - MySQLi 准备好的语句正在悄悄地破坏我的数据。这是预期的行为吗?

javascript - 如何在超时时自动隐藏 div

javascript - 当您在 iframe 中单击时,如何在 iframe 的父 div 中添加类?

javascript - 完整的ajax请求或更多路线