Я застрял, пытаясь преобразовать данные из вызова AJAX в view.py
и обратно в 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);
},
});
});
});
просмотров. 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)
Поэтому после получения POST для вызова AJAX я пытаюсь вернуть его, чтобы предупредить его содержимое (отладка). Первое предупреждение song_id
возвращает идентификатор, как и должно, второе даже не запускается. При попытке отладки (я не помню точную ситуацию), когда он запускается, вторая alert()
просто возвращает целую html страницу, а не только ее часть.
ПРИМЕЧАНИЯ: music/player.html
on в основном это контейнер .player
. Он не содержит включений, расширений или блоков, расширяющих другие шаблоны.