我正在构建一个拍卖项目,并且在模板中,当从模板提交的表单进行查看时,我要进行AJAΧ调用,以便重新加载页面而不刷新,但有时会出错。尽管调用成功,但是新值不会一直显示,尽管数据库中已更改。当我按F5时,将显示新值。
live-auction-details.html
<form id="bid" >{% csrf_token %}
<input id="auction_id" type="hidden" value="{{ auction.id }}">
<button type="submit">Bid</button>
</form>
<script>
$('#bid').on('submit', function(event){ //bid is the name of the form
$.ajax({
method: 'POST',
url: '{% url 'auction:live-auction-details' auction.id %}',
data: {
auction_id: $('#auction_id').val(),
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
},
success: function(data) {
console.log(data);
}
});
});
views.py
def live_auction_details(request, pk):
try:
auction = Auction.objects.get(id=pk, status=1)
except Auction.DoesNotExist:
raise Http404("auction not found")
if request.method == 'POST':
// update records in database
if request.user.is_authenticated():
# can user bid ?
if request.user.player.credits >= auction.credit_charge:
player_can_bid = True
# is player registered ?
if AuctionPlayers.objects.filter(auction_id=auction, auction_player_id=request.user.player.id):
player_is_registered = True
context = {
'auction': auction,
'player_can_bid': player_can_bid,
'player_is_registered': player_is_registered,
}
return render(request, 'auction/live-auction-details.html', context)
答案 0 :(得分:2)
AJAX所做的是对服务器的异步请求,它将根据是否可以完成所需的操作来发送响应。要更新值,必须手动进行,因为可以说这不是实时的。
如果请求的响应成功,则必须在成功函数中更新视图的字段。
例如:
$.ajax({
method: 'POST',
url: 'your_endpoint',
data: your_data_object
dataType: 'json', // If you are using an API RestFul
success: function(response) {
// Here you have to update your view in order to show the changes
// This is an example code
$("#input").val(response.newValue);
}
});