如何将值从javascript函数传递到django视图

时间:2013-10-29 15:45:19

标签: javascript django view

我的问题是,将值从javascript函数传递到django视图的更好方法。

我有一个模板,我通过javascript函数获取值,我想将该值传递给django视图。

2 个答案:

答案 0 :(得分:3)

这个问题很普遍,但这是一种做法。您可以使用jQuery来进行这样的AJAX调用:

        $.ajax({type: 'POST',
                url: '/fetch_data/',                            // some data url
                data: {param: 'hello', another_param: 5},       // some params  
                success: function (response) {                  // callback
                    if (response.result === 'OK') {
                        if (response.data && typeof(response.data) === 'object') {
                            // do something with the successful response.data
                            // e.g. response.data can be a JSON object
                        }
                    } else {
                        // handle an unsuccessful response
                    }
                }
               });

你的Django视图会是这样的:

def fetch_data(request):
    if request.is_ajax():
        # extract your params (also, remember to validate them)
        param = request.POST.get('param', None)
        another_param = request.POST.get('another param', None)

        # construct your JSON response by calling a data method from elsewhere
        items, summary = build_my_response(param, another_param)

        return JsonResponse({'result': 'OK', 'data': {'items': items, 'summary': summary}})
    return HttpResponseBadRequest()

这里显然省略了许多细节,但您可以将其作为指南。

答案 1 :(得分:1)

这里有两种方式:

  1. Ajax请求到您的视图
  2. 将用户重定向到您的值为查询参数
  3. 的新网址
相关问题