我的 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/