無需重新加載頁面即可刷新值的 AJAX 調用不會一直顯示新值

米諾斯

我正在構建一個拍賣項目,並且在模板中,當從模板提交表單以查看時,我正在進行 AJAΧ 調用,以便在不刷新的情況下重新加載頁面,但有時會出現問題。儘管調用成功,但儘管在數據庫中發生了更改,但不會始終顯示新值。當我點擊 F5 時會顯示新值。

現場拍賣-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);
        }
    });
});

視圖.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)
佩佩·盧喬

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);
  }
});

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章