javascript - 从 JSON 响应追加到 JQuery
问题描述
我正在尝试从 HTML 块内的响应中添加数据
我做了什么
...
success: function () {
console.log($("#re-side-cart-items"))
$.getJSON('/cart.js', function (cart) {
$.each(cart.items, function (index, element) {
if(element.id == rewards_variant_id){
console.log($("#re-sidecart-item-template").html());
$("#re-side-cart-items").append($("#re-sidecart-item-template").html())
}
})
});
},
....
我的 HTML 块被分配给这个
var htmlwid = $("#re-sidecart-item-template").html();
<div id="re-sidecart-item-template" class="hide">
"<div class=cart-product row id=" + element.id + ">"
<div class="col-lg-3 col-md-3 col-sm-4 product-img">
<div class="image">
<div class="aspect-container">
<img src="element.img" alt="element.handle" loading="lazy" />
</div>
</div>
</div>
<div class="col-lg-8 col-md-8 col-sm-7 product-info">
<div class="product-title">
<a href="/pages/program" target="_blank">element.title element.price/mo.</b></a>
</div>
</div>
</div>
</div>
我想从响应中获取元素值,它基本上没有按应有的方式工作。
解决方案
我能够修复它
success: function () {
if (window.location.pathname == '/cart'){
window.location.href = "/cart";
}
else{
$.getJSON('/cart.js', function (cart) {
$.each(cart.items, function (index, element) {
if(element.id == rewards_variant_id){
$("#re-side-cart-items").append($('<div>').attr('id', element.id).attr('class', 'cart-product row')
.append($('<div>').attr('class', 'col-lg-3 col-md-3 col-sm-4 product-img')
.append($('<div>').attr('class', 'image')
.append($('<div>').attr('class', 'aspect-container')
.append($('<img>').attr('src', element.image).attr('alt', element.product_title).attr('loading', 'lazy')))))
.append($('<div>').attr('class', 'col-lg-8 col-md-8 col-sm-7 product-info')
.append($('<div>').attr('class', 'product-title')
.append($('<a>').attr('href', element.url)
.append(element.product_title + ' ' + element.price/100 + '/mo.')
)
.append($('<div>').attr('class', 'cart-pricing')
.append($('<a>').attr('href', '/cart/change?line='+element.index+'&quantity=0').attr('data-line', element.id)
.append('<u>Remove</u>')
))
))
);
}
})
});
}
},
推荐阅读
- javascript - 如何使用 Javascript 过滤已加载 JSON 数据的表
- numpy - 不同形状的 NumPy 数组的元素乘法
- javascript - 为什么在“LocalStorage”中添加/删除元素不起作用?
- java - Java10:Hibernate 5.3:包 org.hibernate.annotations 不可访问
- php - 从 Dropbox 下载并上传给用户
- sql-server - 根据某些特定条件计算损益
- javascript - 为什么我不能将承诺(或链式承诺)的结果存储在变量中?
- python - 使用 5.0V 而不是 3.3V 与 Raspberry Pi GPIO 'in' 引脚
- javascript - 从文本中删除内联样式
- android - 异常:CursorIndexOutOfBoundsException:请求索引 0,大小为 0