这是我的AJAX代码,我想使用它从API获取数据以显示在div
中。当我查询数据时,我得到value.application_icon
是null
所以这个文件是空白的
当value.application_icon
为null
时,我想使用value.application_image
。我不知道如何配置这个
$.ajax({
type: "GET",
contentType: "application/json",
url: endpoint + apiKey,
success: function(response) {
$.each(response, function(key, value) {
$('.first-set').append(
'<li><a href="' + value.application_base_url + '' + value.application_url + '"> n ' +
'<div> n ' +
'<i class="' + value.application_icon + '"></i> n ' +
'</div>' +
'<span>' + "Search" + '</span>' +
'</a></li>'
);
})
},
$.ajax({
type: "GET",
contentType: "application/json",
url: endpoint + apiKey,
success: function(response) {
$.each(response, function(key, value) {
var icon = !value.application_icon? value.application_image: value.application_icon;
$('.first-set').append(
'<li><a href="' + value.application_base_url + value.application_url + '"> n ' +
'<div> n ' +
'<i class="' + icon + '"></i> n ' +
'</div>'+
'<span>Search</span>' +
'</a></li>'
);
});
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
});
试试这个代码片段。
$.ajax({
type: "GET",
contentType: "application/json",
url: endpoint + apiKey,
success: function(response) {
$.each(response, function(key, value) {
var icon = value.application_icon;
if (!icon) {
icon = value.application_image;
}
if (icon) {
$('.first-set').append(
'<li><a href="' + value.application_base_url + value.application_url + '"> n ' +
'<div> n ' +
'<i class="' + icon + '"></i> n ' +
'</div>'+
'<span>Search</span>' +
'</a></li>'
);
}
});
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
});
或者像这样使用for loop
$.ajax({
type: "GET",
contentType: "application/json",
url: endpoint + apiKey,
success: function(response) {
for(var i=0; i<response.length; i++) {
var value = response[i];
var icon = value.application_icon;
if (!icon) {
icon = value.application_image;
}
if (icon) {
$('.first-set').append(
'<li><a href="' + value.application_base_url + value.application_url + '"> n ' +
'<div> n ' +
'<i class="' + icon + '"></i> n ' +
'</div>'+
'<span>Search</span>' +
'</a></li>'
);
}
});
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
});
希望对你有帮助。