【问题标题】:How to pass value from javascript function to django view如何将值从 javascript 函数传递到 django 视图
【发布时间】:2013-10-29 15:45:19
【问题描述】:

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

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

【问题讨论】:

    标签: javascript django view


    【解决方案1】:

    这个问题很笼统,但这里有一种方法。您可以使用 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()
    

    这里很多细节明显省略了,但你可以以此为指导。

    【讨论】:

      【解决方案2】:

      这里有两种方式:

      1. Ajax 请求到您的视图
      2. 将用户重定向到您的值为查询参数的新 URL

      【讨论】:

      • 你有任何使用ajax的例子吗?我是新人
      • @Jmint:这超出了这个问题的范围(老实说,这个网站)。如果您熟悉 jquery,请从 sitepoint.com/ajax-jquery 开始学习 jquery AJAX。 Google 将帮助您找到使用 vanilla javascript 的 AJAX 教程
      猜你喜欢
      • 2015-01-21
      • 2019-08-25
      • 2020-06-08
      • 2014-09-09
      • 1970-01-01
      • 2015-11-09
      • 1970-01-01
      • 1970-01-01
      • 2021-03-26
      相关资源
      最近更新 更多