Warm tip: This article is reproduced from stackoverflow.com, please click
ajax django javascript jquery json

DJANGO

发布于 2020-03-31 22:57:27

I'm stuck trying to convert data from the AJAX call to view.py and back to HTML:

JQuery/Javascript

    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = cookies[i].trim();
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

    function csrfSafeMethod(method) {
        // these HTTP methods do not require CSRF protection
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }

    $(document).ready(function(){ 

        var csrftoken = getCookie('csrftoken');

        $.ajaxSetup({
            beforeSend: function(xhr, settings) {
                if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                    xhr.setRequestHeader("X-CSRFToken", csrftoken);
                }
            }
        });

        // AJAX CALL TO VIEW
        $('a.play').click(function(e){
            e.preventDefault();
            var song_id = $(this).attr('id');
            alert(song_id);
            $.ajax({
                url: $(this).data('href'),
                type: 'POST',
                content: 'application/json; charset=utf-8',
                data: {
                    'song_id': song_id
                },
                dataType: 'json',
                success: function(html) {
                    alert(html);
                    $('.player').replaceWith(html);
                },
            });
        });
    });

views.py

    from django.shortcuts import render
    from django.http import Http404, JsonResponse
    from django.core import serializers
    from django.template.loader import render_to_string

    from .models import Song

    def change_song(request):
        if request.method == "POST":
            request.session['featured_song'] = request.POST.get('song_id', '')
            featured_song_id = request.session['featured_song']
            obj = Song.objects.get(pk=featured_song_id)
            song_list = Song.objects.all().order_by('-date') # list of objects
        context = {
            "featured_song": obj,
            "song_list": song_list,
        }
        return render_to_string("music/player.html", context)

Therefore, after receiving the POST for the AJAX call, I try to return it to alert its content (debugging). The first alert song_id returns the id as it should, the second does not even run. When trying to debug (I don't remember the exact situation), when it runs, the second alert() just returns the WHOLE html page, not just the portion.

NOTES: music/player.html on the view is basically the .player container. It is void of includes or extends or blocks that extend other templates.

Questioner
user3291759
Viewed
44
user3291759 2020-01-31 19:37

So, I ended up resolving the issue. It was an template/url issue all along...

I was trying to access the sub APP url path href="/change/" and didn't fill the complete URL for the APP href="/music/change/". My thought process was that, since the template was inside the template folder in 'music' APP, the URL only needed the /change/ part of the URL.

That being said, I will still post the code here for future reference since I also fixed some JSON handling, in case someone needs to use something similar.

views.py

def change_song(request):
    featured_song_id = request.session['featured_song']
    song_list = Song.objects.all().order_by('-date') # list of objects
    if request.method == "POST":
        request.session['featured_song'] = request.POST['song_id']
        featured_song_id = request.session['featured_song']
    obj = Song.objects.get(pk=featured_song_id)
    serialized_obj = serializers.serialize('json', [obj])
    serialized_song_list = serializers.serialize('json', song_list)
    string_render = render_to_string('music/player.html')
    context = {
        'html': string_render,
        'obj': serialized_obj,
        'song_list': serialized_song_list,
    }
    return JsonResponse(context, safe=False)

AJAX/jQuery/Javascript

    $('a.play').click(function(e){
        e.preventDefault();
        var song_id = $(this).attr('id');
        var this_url = $(this).attr('href');
        $.ajax({
            type: 'POST',
            url: this_url,
            data: {
                'song_id': song_id,
            },
            dataType: 'json',
            success: function(data) {
                obj = JSON.parse(data.obj);
                title = obj[0]['fields']['title'];
                $('.replace').replaceWith(data.html);
                $('.player-title').html(title);
            }
        });
    });