1

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

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

4

2 回答 2

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()

这里显然省略了许多细节,但您可以以此为指导。

于 2013-10-29T20:45:44.347 回答
1

这里有两种方法:

  1. Ajax 请求到你的视图
  2. 将用户重定向到您的值为查询参数的新 URL
于 2013-10-29T15:57:18.363 回答