更新时间:2023-10-24 08:30:16
如果您正在ajax成功处理程序中执行,因为您正在ajax中执行$.parseJSON(data)
$.parseJSON(data)
成功处理程序,问题几乎可以肯定是jQuery已经已经为您解析了它. jQuery将查看响应的Content-Type
,如果响应为application/json
,它将对其进行解析,并将解析的结果提供给成功处理程序.如果将其传递给$.parseJSON
,将会发生的第一件事是它将被转换回字符串(对于您来说是"[object Object]"
),然后$.parseJSON
将无法解析该字符串.
If you're doing the Since you're doing the $.parseJSON(data)
in an ajax success handler$.parseJSON(data)
in an ajax success handler, the problem is almost certainly that jQuery has already parsed it for you. jQuery will look at the Content-Type
of the response and, if it's application/json
, it will parse it, and provide the parsed result to your success handler. The first thing that will happen if you pass that into $.parseJSON
will be that it will get converted back to a string ("[object Object]"
, in your case), which $.parseJSON
will then fail to parse.
只需按原样使用data
,就已经有了对象,这要归功于自动解析:
Just use data
as-is, it's already an object, thanks to the automatic parsing:
$(document).ready(function() {
$('#branchAndSubjects').click(function() {
$.post('/findBranchAndSubjects', {
roll: roll,
_token: "{{csrf_token()}}"
}, function(data) {
console.log(data.year); // 3
console.log(data.subjects.length); // 4
console.log(data.subjects[0].name); // Control Systems
});
});
});