javascript 为什么 AJAX 会触发django中的500内部错误?

oaxa6hgo  于 2023-01-01  发布在  Java
关注(0)|答案(1)|浏览(135)

Does anyone know why I am getting 500 internal error when I try to call an Ajax function? I tried to send the response from view.py to Ajax function in 2 ways: JsonResponse (see else from view.py) and also with HttpResponse (see if from View.py).
我的Hmtl表单确实有一个csrf_token,所以我在ajax函数中添加了头,但仍然得到了500个内部错误。数据被保存到数据库中,但响应没有发送到ajax函数。

    • 查看. py**
## Ajax
@login_required
def SubmitModal(request):
    if request.method == 'POST':
        text = request.POST['Text']
        date = request.POST['DatePicker']
        time = request.POST['TimePicker']
        
        T = SText()
        
        T.User = request.user
        T.Text = text
        T.STime = date + ' ' + time
        T.save()

        return HttpResponse(json.dumps({'success': True}), content_type="application/json")
    else:
        return JsonResponse({'success': False})
    • 包含ajax的文件**
$(document).ready(function () {
    // Show the modal window when a button is clicked
    $('#open-modal').click(function () {
        $('#modal').modal('show');
    });

    // Close the modal window when a button is clicked
    $('.close-modal').click(function () {
        $('#modal').modal('hide');
    });
    
    // Handle the form submission
    $('#modal-form').submit(function (event) {
        event.preventDefault(); // Prevent the form from being submitted
        var formData = $(this).serialize(); // Get the form data
        // Submit the form data to the server using an AJAX request
        $.ajax({
            type: 'POST',
            url: '/submit/',
            headers: {'X-CSRFToken': '{{ csrf_token }}'},
            data: formData,
            dataType: "json",
            success: function (response) {
                if (response.success) {
                    $('#success-message').show();
                } else {
                    $('#error-message').show();
                }
            },
             error: function (xhr, status, error) {
        console.log(error);
    }
        });
        $(".textarea-input")[0].value = '';
        $(".date-input")[0].value = '';
        $(".time-input")[0].value = '';
    });
});
dvtswwa3

dvtswwa31#

如果你要在非生产环境中重现这个问题,你可以在设置文件中设置DEBUG=True。然后当你从浏览器调用时,响应将包括关于问题的详细信息。你也可以设置ADMINS变量,以便在遇到指定的电子邮件时向它们发送异常跟踪。更多详细信息请点击此处。
您可以在所用浏览器的开发者工具中查看正在发送和接收的数据。

相关问题