jquery - I want to know why an error occurred when I sent an array to view with jquery ajax (django,jquery)
问题描述
hello I have a question
I am trying to implement row delete with jquery ajax.
I sent an array to view in jquery ajax
At this time error has occured. The contents of the error are as follows.
error message:
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\django_inflearn2\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\django_inflearn2\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\django_inflearn2\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\django_inflearn2\todo\views.py", line 23, in todo_delete_ajax
todo_ids = request.POST['todo_arr']
File "C:\django_inflearn2\venv\lib\site-packages\django\utils\datastructures.py", line 80, in __getitem__
raise MultiValueDictKeyError(key)
django.utils.datastructures.MultiValueDictKeyError: 'todo_arr'
[02/Jun/2019 06:11:29] "POST /todo/todo_delete_ajax/ HTTP/1.1" 500 19607
if you know what is the reason and how fix plase let me know
thanks~!
jquery , ajax
$('#todo_delete_button').click(function(e){
e.preventDefault();
// todo_check
alert("삭제 버튼 ")
// Get checked checkboxes
var todo_arr = [];
$('.td_check').each(function() {
if (jQuery(this).is(":checked")) {
var id = this.id;
todo_arr.push(id);
}
});
alert('todo_arr : '+ todo_arr)
$.ajax({
type: "POST",
url: 'todo_delete_ajax/',
data: {
todo_arr:todo_arr,
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success: function(result) {
alert('todo_delete_ajax is success ');
}
});
})
and
url pattern
path('todo_delete_ajax/',views.todo_delete_ajax, name ="todo_delete_ajax"),
view
def todo_delete_ajax(request):
# print("request " , request )
todo_ids = request.POST['todo_arr']
print("todo_ids : ", todo_ids)
return redirect('/todo/')
解决方案
我看到您只是试图将选中的复选框的 ID 发送到服务器。
这意味着如果没有选中的复选框,则todo_arr变为null
您需要以这种方式给这种情况一个机会:
def todo_delete_ajax(request):
todo_ids = request.POST.get("todo_arr", None)
// check if there are any todos
if todo_ids:
print("todo_ids : ", todo_ids)
return redirect('/todo/')
// else, do something else
request.POST.get 确保如果todo_arr为空,则todo_ids为 None。你得到那个错误是因为你试图得到不存在的东西。
推荐阅读
- javascript - Typescript 的界面问题 - Angular 7
- c++ - 复杂的 std::map、结构、std::deque 问题
- javascript - Ionic JavaScript 函数无需等待承诺即可执行
- python - 用python对象中的数字替换字母
- javascript - 在 React 中的表上创建可扩展行的简单方法是什么?
- javascript - 如何通过使用 jQuery 或 JS 在特定 li 上单击事件来添加 ul 和 li
- ionic-framework - 如果我更改 common.d.ts ionic serve 正常运行的原因
- css - 过渡变换时如何阻止Chrome切断CSS模糊过滤器
- angular - Angular 8 路由器在尝试激活同一路由时不会触发任何带有 `onSameUrlNavigation: 'reload'` 的事件
- java - Java Testcontainers - 无法连接到暴露的端口