Python 在django中将列表从jquery传递给视图函数
假设我在django项目中有以下函数。getValues2()返回带有数字的列表。如何使用window.location将这些数字传递到视图Python 在django中将列表从jquery传递给视图函数,python,jquery,django,Python,Jquery,Django,假设我在django项目中有以下函数。getValues2()返回带有数字的列表。如何使用window.location将这些数字传递到视图 <script> let getValues2 = () => $("input[name='checkb']:checked").map((i,el) => el.id.trim()).get(); console.log('getValues2 ',getValues2()) window.l
<script>
let getValues2 = () => $("input[name='checkb']:checked").map((i,el) => el.id.trim()).get();
console.log('getValues2 ',getValues2())
window.location('eprint/checked' + getValues?()
</script>
在你的JS中
如果需要保护,还需要CSRF的JS Cookie库()
您必须从js向django中的特定url执行AJAX调用才能在视图中接收。我在尝试上述操作时遇到此错误:window.location不是函数我遇到了一个奇怪的错误:TypeError:send_to_view()。然后(…)。然后(…)。错误不是函数对不起,应该是这样的。最后捕获。我已经更新了答案。
def eprint(request):
print('eprint')
# how to get the list from jquery?
print(checked)
<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>
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"})