gpt4 book ai didi

jquery - 使用Django的JSONResponseMixin响应AJAX请求

转载 作者:行者123 更新时间:2023-12-01 01:24:25 25 4
gpt4 key购买 nike

我正在使用 Django 和 AJAX。基本上,我只是想让 javascript (vote.js) 发布一些数据到 Django View ,然后 View 以 JSON 数据响应 html,以便我的 javascript 回调函数可以使用来自服务器的响应。

这是我的代码:

vote.js

$(document).on('click', 'a.upvote', function() {
.....

var xhr = {
'id': id,
'upvote': upvote,
};

$.post(location.href, xhr, function(data) {
question.find('.rating').html(data.rating)
});

return false;
});

views.py

//I copied this JSONResponseMixin directly from official Django doc
class JSONResponseMixin(object):
def render_to_response(self, context):
"Returns a JSON response containing 'context' as payload"
return self.get_json_response(self.convert_context_to_json(context))

def get_json_response(self, content, **httpresponse_kwargs):
"Construct an `HttpResponse` object."
return http.HttpResponse(content,
content_type='application/json',
**httpresponse_kwargs)

def convert_context_to_json(self, context):
"Convert the context dictionary into a JSON object"
# Note: This is *EXTREMELY* naive; in reality, you'll need
# to do much more complex handling to ensure that arbitrary
# objects -- such as Django model instances or querysets
# -- can be serialized as JSON.
return json.dumps(context)


class MyListView(JSONResponseMixin, TemplateResponseMixin, DetailView):
def post(self, request, *args, **kwargs):
id = request.POST.get('id')
.....

data = {'rating': question.rating}

return render_to_response(data)


def render_to_response(self, context):
if self.request.is_ajax():
return JSONResponseMixin.render_to_response(self, context)
else:
return TemplateResponseMixin.render_to_response(self, context)

但是,执行此操作并单击 html 中触发 javascript POST 的“投票”按钮会给我一个 TemplateDoesNotExist 错误:

错误

.....
File "/Library/Python/2.7/site-packages/django/template/loader.py", line 139, in find_template
raise TemplateDoesNotExist(name)
TemplateDoesNotExist: {'rating': 1}

看来我的views.py 的最后5 行工作正常。任何想法??? :(((

谢谢!!!

最佳答案

class MyListView(JSONResponseMixin, TemplateResponseMixin, DetailView):
def post(self, request, *args, **kwargs):
id = request.POST.get('id')
.....

data = {'rating': question.rating}

return render_to_response(data)

你最终在这里调用了错误的render_to_response方法,即django.shortcuts中的快捷方式函数,我猜你已经在views.py中导入了它。

改用return self.render_to_response(data)

关于jquery - 使用Django的JSONResponseMixin响应AJAX请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18172639/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com