【问题标题】:passing a list from jquery to a view function in django将列表从 jquery 传递到 django 中的视图函数
【发布时间】:2021-04-25 13:54:51
【问题描述】:

假设我的 django 项目中有以下功能。 getValues2() 返回一个带有数字的列表。如何使用 window.location 将此数字传递给我的视图?

<script>

  let getValues2 = () => $("input[name='checkb']:checked").map((i,el) => el.id.trim()).get();

  console.log('getValues2 ',getValues2())
  window.location('eprint/checked' + getValues?()

</script>

views.py

def eprint(request):

    print('eprint')
    # how to get the list from jquery? 
    print(checked)

【问题讨论】:

  • 您必须从 js 到 django 中的特定 url 进行 AJAX 调用才能在视图中接收。
  • 尝试上述方法时出现此错误:window.location 不是函数

标签: python jquery django


【解决方案1】:

在你的 JS 中

如果你想要保护,你还需要 CSRF 的 JS Cookie 库 (https://docs.djangoproject.com/en/3.2/ref/csrf/;https://github.com/js-cookie/js-cookie/)

<script>

  let getValues2 = () => $("input[name='checkb']:checked").map((i,el) => el.id.trim()).get();

  console.log('getValues2 ',getValues2())
  
  async function send_to_view(){
     const csrftoken = Cookies.get('csrftoken');
     let response = await fetch(`${url_to_eprint}`, {
     method: 'POST',
     headers: {
          'Content-type':'application/json',
          'X-CSRFToken': csrftoken,
          },

     // JS sends as a string to back end
     body: JSON.strigify(getValues2)
          })
     
     let data = await response.json()
     return data
     }

     send_to_view()
     .then(data => {
          console.log(data)
     })
     .catch(err => {
          console.log(err)
     })
     
  //window.location('eprint/checked' + getValues?()

</script>

在你的意见中.py

import json
from djano.http import JsonResponse

def eprint(request):

    # post request comes in the body of the request
    print(request.body)

    # have to unpack it from a string into a dictionary
    checked = json.loads(request.body)
    print('eprint')
    # how to get the list from jquery? 
    print(checked)

    return JsonResponse({"status":"Okay"})

【讨论】:

  • 我有一个奇怪的错误:TypeError: send_to_view().then(...).then(...).error is not a function
  • 对不起,应该是 .catch 在最后。我已经更新了答案。
猜你喜欢
  • 2013-07-15
  • 2015-11-09
  • 2020-06-08
  • 1970-01-01
  • 2018-06-26
  • 2013-06-24
  • 2020-08-09
  • 2019-05-26
  • 1970-01-01
相关资源
最近更新 更多