简体   繁体   中英

Django: Update Page Information Without Refreshing

I've been trying to make this portion of my website update whenever a button is pressed:

硬币

In my template, I access this information through {{ request.user.profile.coins }} :

<span class="status">Balance:&nbsp;{{ request.user.profile.coins }}
  <img class="coin-img" src="{% static 'assets/coin.png' %}" height="40px" width="auto">
</span>

I was looking into the process and I attempted to use an AJAX function to call this view:

@login_required(login_url='users/login')

def coin_increase(request):
    """
    Function based view for increasing a user's coin balance
    """
    if request.is_ajax():
        try:
            user = request.user
        except User.DoesNotExist:
            raise Http404("No user matches the given query.")
        user.profile.coins += 5
        user.save()
        return render(request, 'home.html', {'home': home})
    else:
        raise Http404

The AJAX function is as follows:

function update_coins() {
    $.ajax({
      method: "POST",
      url: "/coins",
      data: {},
      success: function(data) {
        alert("test");
      }
    })
  };

How can I get this to work?

I guess that home.html is the template of the whole page, which contains the portion of interest.

The problem is here:

return render(request, 'home.html', {'home': home})

You don't need to render the whole page to update just that portion. You only need to know the new value for user.profile.coins . The most used technique is to serialize that data into a format that javascript can understand: JSON.

Not sure about what is your version of django, maybe this will work:

from django.http import JsonResponse
return JsonResponse({'coins':user.profile.coins})

Then:

function update_coins() {
    $.ajax({
      method: "POST",
      url: "/coins",
      data: {},
      success: function(data) {
        console.log(data) // check out how data is structured

        // Update the coin amount
        $('.status').contents()[0].textContent = 'Balance&nbsp'+data.coins
      }
    })
  };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM