我想用通过html
调用检索到的数据更新AJAX
模板。
我可以获取数据并在JS
中定义变量。但是,如何从JS
到Html
取值,以更新Html
“药丸”中的值?
<span class="badge badge-primary badge-pill">0</span>
即将值从0更改为var CarPrice = data.carPrice
中定义的值; ?
JS:
$(function () {
var getProduct) = function () {
var btn = $(this);
$.ajax({
url: btn.attr("data-url"),
type: 'get',
dataType: 'json',
success: function (data){
var CarMake = data.carMake
var CarPrice = data.carPrice
$("#CarMake").val(CarMake);
$("#CarPrice").val(CarPrice);
}, error: function(error){
console.log(error)
console.log("error")
}
});
};
$(".js-get-product").click(getProduct);
});
HTML(django):
<div class="container">
<h3>Key Metrics</h3>
<div class="row">
<div class="col-sm-4">
<div class="card text-dark bg-light">
<div class="card-header bg-dark text-center text-light"><h4>CARS</h4></div>
<div class="card-body ">
<h5 class="card-title">Car Details/h5>
<!--Starting list group here -->
<div class="list-group">
<a class="list-group-item d-flex justify-content-between align-items-center list-group-item-action list-group-item-primary">
Car Make
<span class="badge badge-primary badge-pill">0</span>
</a>
<a class="list-group-item d-flex justify-content-between align-items-center list-group-item-action list-group-item-danger">
Car Price
<span class="badge badge-primary badge-pill">0</span>
</a>
</div>
<!--Ends here -->
</div>
<div class="card-footer bg-secondary border-danger text-right">
<a
class="btn btn-success btn-sm js-get-product"
data-url="{% url 'api-product' object.product_uid %}">Get Details</a>
</div>
</div>
</div>
</div>
</div>
答案 0 :(得分:1)
您是否尝试过jQuery的text()
方法?我通过ID更新了0
值。您的CarMake和CarPrice未在span元素中分配。
像这样:
<a class="list-group-item d-flex justify-content-between align-items-center list-group-item-action list-group-item-primary">
Car Make
<span id="CarMake" class="badge badge-primary badge-pill">0</span>
</a>
<a class="list-group-item d-flex justify-content-between align-items-center list-group-item-action list-group-item-danger">
Car Price
<span id="CarPrice" class="badge badge-primary badge-pill">0</span>
</a>
$(function () {
var getProduct) = function () {
var btn = $(this);
$.ajax({
url: btn.attr("data-url"),
type: 'get',
dataType: 'json',
success: function (data){
var CarMake = data.carMake
var CarPrice = data.carPrice
$("#CarMake").text(CarMake);
$("#CarPrice").text(CarPrice);
}, error: function(error){
console.log(error)
console.log("error")
}
});
};
$(".js-get-product").click(getProduct);
});