我一直在尝试将数据从AJAX调用转换view.py
为HTML并重新转换为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)
因此,在收到AJAX调用的POST之后,我尝试将其返回以提醒其内容(调试)。第一个警报song_id
按原样应返回ID,第二个警报甚至不会运行。当尝试调试时(我不记得确切的情况),当它运行时,第二个alert()
仅返回整个html页面,而不仅仅是该部分。
注意:
music/player.html
在视图上基本上是.player
容器。它没有包含,扩展或扩展其他模板的块。
因此,我最终解决了这个问题。一直是模板/网址问题...
我想访问子APP的URL路径href="/change/"
,但没有填写APP的完整URL href="/music/change/"
。我的想法是,由于模板位于“音乐” APP的模板文件夹中,因此该URL仅需要该URL的/change/
一部分。
话虽如此,我仍然在这里发布代码以供将来参考,因为我还修复了一些JSON处理,以防万一有人需要使用类似的东西。
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);
}
});
});