在使用Postman进行API调用并得到结果后,我尝试在下面的成功函数中获取“KC Content Kind ID”值的对应ID。但由于它不是一个数组,我想知道在jQuery中是否可以使用“each”方法,并如何处理。我想通过进入facet对象来遍历这个嵌套的JSON对象,如果名称属性为“KC Content Kind ID”,则返回相应名称属性的ID。
"results": {
"data": {
"facets": {
"60749428": {
"id": 60749428,
"name": "KC Content Content Kind"
},
"60750276": {
"id": 60750276,
"name": "KC Content Product Version"
},
"69107204": {
"id": 69107204,
"name": "KC Video Audience"
},
"69127027": {
"id": 69127027,
"name": "KC Content Kind ID"
}
}
}
}
这是我的代码,我正在使用成功函数(success function)
function getAvailableKinds() {
$.ajax({
url: csexe + "/api/v2/facets/" +getLocationId(),
dataType: "json",
type: "GET",
beforeSend: function(xhr) {
xhr.setRequestHeader ("OTCSticket", getAuthToken());
},
success: function(response) {
var obj = response.results.data.facets;
$.each(obj, function(item, value){
if ( value.name == 'KC Content Kind ID') {
var idRequired = obj.id;
}
});
},
error: function(jqXHR, textStatus, errorThrown){
alert("An error occurred... Look at the console");
$("body").html('<p>status code: '+jqXHR.status+'</p><p>Error Thrown: ' + errorThrown + '</p><p>Response Text:</p><div>'+jqXHR.responseText + '</div>');
}
});