django - 通过基于类的视图将数据从服务器传递到js函数

时间:2014-06-07 17:23:48

标签: django

Django 1.6.3 +

需要将数据传递到基于类的视图。我希望我的jquery函数处理从服务器传递的数据。怎么做?

2 个答案:

答案 0 :(得分:1)

1。 在视图中创建一个javascript / jquery函数,它生成$ .ajax({options});拨打您要发送的网址&接收数据(参见#4)。

2。 让你的views.py文件导入json& HttpResponse模块。

import json
from django.http import HttpResponse

3。 在views.py中添加一个函数来处理请求

def ExampleHandler(request):

在此功能中,您可以访问request.POST [' paramname']或request.GET [' paramname']等参数。有关详细信息,请参阅https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest.GET

要将数据返回到ajax调用,请将数据存储在如下字典中:

result = {
    'success': True,
    'foo': bar,
    'more': data
}

并像这样返回json:

return HttpResponse(json.dumps(result), content_type="application/json")

4

您原来的javascript函数现在看起来与此类似:

function exampleRequest() {
    $.ajax({
        type: 'POST',
        url: '/url-mapped-to-your-view',
        data: {data: 'some-data-to-send-to-views'},  // May need to add a CSRF Token as post data (eg: csrfmiddlewaretoken: "{{ csrf_token }}")
        error: function() {
            alert('There was an issue getting the data...');
        },
        success: function(data) {
            // Accessing data passed back from request, handle it how you wish.
            alert(data.foo);
            alert(data.more);
        }
    )};
}

5。 确保您进行ajax调用的url已正确映射到urls.py

答案 1 :(得分:0)

您可以通过argskwargs

传递数据 在views.py中

class YourView(TemplateView):

    def get_context_data(self, **kwargs):
        context = super(YourView, self).get_context_data(**kwargs)
        context['yourdata'] = self.kwargs['data']
        return context
在urls.py中

url(r'(?P<data>\w+)$', YourView.as_view()),