[英]how to display image get from ajax response
$.ajax({
url: "https://developers.zomato.com/api/v2.1/search?entity_id=52&entity_type=city&start=0&count=20",
dataType: 'json',
async: true,
beforeSend: function (xhr) {
xhr.setRequestHeader('user-key', '');
},
success: function (response) {
var s = "";
var i = 0;
var res_Arr = response.restaurants;
$.each(res_Arr, function (index, value) {
var res_img = res_Arr[i].restaurant.featured_image;
s = s + '<img src="' + res_img + '"/>';
i = i + 1;
})
$('#result').text(s);
}
});
我嘗試在線搜索並嘗試了多種方法,但我無法發現我犯的錯誤……我的控制台沒有顯示任何錯誤。 我想顯示為圖像,但它顯示的是圖像鏈接......
使用jQuery
的append()
方法在網頁中渲染 html。
$('#result').append(s);
考慮以下代碼。
$.ajax({
url: "https://developers.zomato.com/api/v2.1/search?entity_id=52&entity_type=city&start=0&count=20",
dataType: 'json',
async: true,
beforeSend: function (xhr) {
xhr.setRequestHeader('user-key', '');
},
success: function (r) {
$.each(r.restaurants, function (i, v) {
$("<img>", {
src: v.featured_image
}).appendTo($('#result');
});
}
});
當 AJAX 成功時,這將使用$.each()
根據響應創建一個新圖像,並附加來自restaurants
對象的每個圖像。
查看更多: https : //api.jquery.com/jquery.each/
$.each()
函數可用於迭代任何集合,無論是對象還是數組。 在數組的情況下,回調每次都會傳遞一個數組索引和相應的數組值。 (該值也可以通過this
關鍵字訪問,但 Javascript 將始終將this
值包裝為一個對象,即使它是一個簡單的字符串或數字值。)該方法返回它的第一個參數,即被迭代的對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.