Javascript 如何通过密钥访问json数组
打印时:Javascript 如何通过密钥访问json数组,javascript,jquery,json,x-editable,Javascript,Jquery,Json,X Editable,打印时:console.log(响应) 它给了我这个json数组: { "myStudentId":17, "myName":"beng", "myAge":38, "myAddress":"Los Angeles, California, USA.", "myGender":"Female", "myReligion":"Catholic", "myStatus":"boom", "myOccupation":"Actre
console.log(响应)代码>
它给了我这个json数组:
{
"myStudentId":17,
"myName":"beng",
"myAge":38,
"myAddress":"Los Angeles, California, USA.",
"myGender":"Female",
"myReligion":"Catholic",
"myStatus":"boom",
"myOccupation":"Actress",
"myEducationLevel":"Undefined",
"graduate":true
}
我想访问graduate
值。到目前为止,我尝试的是:
console.log( response["graduate"] );
console.log( response.graduate );
但这一切都返回未定义的。有办法做到这一点吗?如果可能的话,我不想使用循环。如果可能的话,我想通过密钥访问它
编辑:
我在用手机回电话
$(this).editable({
pk: pk,
name: id,
url: '../admin/edit_studentInfo.do',
validate: function( value ) {
if($.trim( value ) == '') {
return 'This field is required';
} else if( isNaN( value ) && id == 'age' ) {
return 'Only accepts numbers';
}
},
success: function(response, newValue) { // call back
var test = response;
console.log( JSON.stringify(response) );
console.log( response );
console.log( response["graduate"] );
console.log( response["myName"] + ', ' + response.myName );
}
});
我包括了可编辑的初始化和测试添加ajaxOption
ajaxOptions: {
dataType: 'json'
}
响应
是一个字符串。您需要将其解析为JSON,然后才能访问编码对象的任何属性:
response = JSON.parse(response);
console.log(response.graduate);
或者,告诉use或passdataType:“JSON”
,jQuery将为您进行解析。这是一个对象,而不是一个arraycab,您说console.log(JSON.stringify(response))
我觉得您也可以1。仍然有一个字符串作为响应(jQuery“intelligent guess”有时会失败)2。执行异步调用时出错。最好将剩下的代码发布在这里。如果您通过ajax解析它,请确保使用数据类型:“JSON”@samitha,我会研究它。我用它来回应,很有魅力。谢谢