【发布时间】:2018-03-09 12:29:08
【问题描述】:
我有这个 ajax 帖子,工作得很好,所以它运行函数 test 将 data 传递给它。
$("#formID").submit(function (event) {
$('#postError').html('').hide();
$('#postInfo').html('loading results').show();
event.preventDefault();
$.ajax({
type: 'POST',
url: $("#formID").attr('action'),
data: $(this).serialize()
})
.done(function (data) {
$('#postInfo').html('').hide();
test(data);
})
.fail(function () {
$('#postInfo').html('').hide();
console.log(1);
});
})
这就是问题所在,
function test(data) {
console.log(data);
if ($.isArray(data)){
$('#postSuccess').html(data).show();
}else {
$('#postError').html(data).show();
}
}
这是我在 console.log 中得到的:
[{"a1":"1","a1amount":"300","a2":"2","a2amount":"300","a3":"3","a3amount":"300"
,"a4":"4","a4amount":"300","a5":"5","a5amount":"60"},
{"b1":"6","b1amount":"75","b2":"7","b2amount":"75","b3":"8","b3amount":"75"},
{"c1":"9","c1amount":"40","c2":"10","c2amount":"40","c3":"11","c3amount":"40"," c4":"12","c4amount":"40"}]
这是一个普通的 json 数组对还是我错了? 如果我是对的,那么我想知道它为什么运行 else 部分 如果我错了,那么我想知道函数或数组有什么问题。
【问题讨论】:
-
我确定你得到的是一个字符串而不是一个数组。即:
'[{"a1":"1","a1amount":"300","a2":"2","a2amount":"300","a3":"3","a3amount":"300" ,"a4":"4","a4amount":"300","a5":"5","a5amount":"60"}, {"b1":"6","b1amount":"75","b2":"7","b2amount":"75","b3":"8","b3amount":"75"}, {"c1":"9","c1amount":"40","c2":"10","c2amount":"40","c3":"11","c3amount":"40"," c4":"12","c4amount":"40"}]'- 但是,Console.log(data)将其打印为对象。您需要先将字符串解析为对象。使用JSON.parse(data) -
是的,确实有效,谢谢。
标签: javascript arrays json ajax