【问题标题】:AJAX call to refresh values without reloading page doesn't show new values all the times无需重新加载页面即可刷新值的 AJAX 调用不会一直显示新值
【发布时间】:2019-04-07 15:10:19
【问题描述】:

我正在构建一个拍卖项目,并且在模板中我正在进行 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)

【问题讨论】:

  • 我注意到您正在将呈现的模板返回给 ajax 调用。你不应该返回 JSON 数据吗?
  • 是的,我会试一试,让你知道

标签: ajax django django-views


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2013-05-28
    • 2021-03-25
    • 1970-01-01
    • 2013-12-15
    • 2011-12-21
    • 1970-01-01
    • 2021-11-19
    • 2012-08-16
    • 2012-04-15
    相关资源
    最近更新 更多