首页 > 解决方案 > 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/')

标签: jqueryarraysajaxdjangoview

解决方案


我看到您只是试图将选中的复选框的 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。你得到那个错误是因为你试图得到不存在的东西。


推荐阅读