我试图减少附加相同div的重复。我使用ajax,我想在每个成功的帖子后传递一个上下文到另一个文件,但它总是导致TemplateSyntaxError。
TemplateSyntaxError at /items/order/2546
Could not parse the remainder: '${data}' from '${data}'
是否有可能在jQuery中做这样的事情,或者我只是做错了?
$.ajax({
url: "{% url 'namespace:name' %}",
headers: {
'X-CSRFToken': csrftoken,
},
data: {
item: "123"
},
method: "POST",
success: (response) => {
let data = JSON.parse(response);
$('#container').append(`{% include "partials/repeating_item.html" with response=${data} %}`);
}
});
partials/repeating_item.html
显示如下图
<div class="list-item item-{{ response.order_id }}">
<a href="#" class="item-name" data-item='{{ response.item_id }}'>
<div class="svg-div">
<!-- some svg -->
<svg width="20px" height="20px" viewBox="0 0 20 20" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"></svg>
</div>
</a>
<div class="item-summary-title">
{{ response.item_name }}
</div>
<div>
<div class="item-price-div">
<div><span>${{ response.item_price }}</span></div>
</div>
</div>
</div>
, ajax响应返回一个对象
{
item_id: 69,
order_id: 2546,
item_name: "X Gaming Chair",
item_price: "399.00"
}
提前感谢!
您可以在ajax的成功函数中创建html
,可以将相同的container
附加到您的div
演示代码 :
let data = {
item_id: 69,
order_id: 2546,
item_name: "X Gaming Chair",
item_price: "399.00"
}
//ajax codes here ..
/*$.ajax({
url: "{% url 'namespace:name' %}",
headers: {
'X-CSRFToken': csrftoken,
},
data: {
item: "123"
},
method: "POST",
success: (response) => {*/
//create that html here ..and add json datas
// let data = JSON.parse(response);
$('#container').append(`<div class="list-item item-${data.order_id }">
<a href="#" class="item-name" data-item='${data.item_id}'>
<div class="svg-div">
<!-- some svg -->
<svg width="20px" height="20px" viewBox="0 0 20 20" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"></svg>
</div>
</a>
<div class="item-summary-title">
${data.item_name}
</div>
<div>
<div class="item-price-div">
<div><span>${data.item_price}</span></div>
</div>
</div>
</div>`);
/*}
})*/
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
</div>