【问题标题】:Django form fields errors not showing in AjaxDjango 表单字段错误未在 Ajax 中显示
【发布时间】:2021-07-28 17:01:29
【问题描述】:

我有一个使用 AJAX 的 Django 表单。该表单按预期工作。现在的问题是输入无效输入时不会显示 Django 表单错误。我按照here 的描述遵循了 Django 表单 API。有没有办法解决这个问题?

main.js

$(document).ready(function(){
    $("#itemForm").on('submit', function (e) {
        e.preventDefault();
        var serializedData = $(this).serialize();
        $.ajax({
            type: 'POST',
            url: "post/ajax/myURL/",
            data: serializedData,
            success: function (data) {
                if($('input[type="checkbox"]').prop("checked") == true){
                    // some codes here
                    $("#itemsTable tbody").prepend(
                        // some codes here
                    )
                    console.log("Checkbox is checked. Modal will not be closed");
                }
                else if($('input[type="checkbox"]').prop("checked") == false){
                    // some codes here
                    console.log("Checkbox is unchecked. Modal will now be closed");
                }
            },
            error: function (jqXHR, textStatus, errorText, data) {
                for (var name in data) {
                    for (var i in data[name]) {
                        $('#ajaxErrorMessage').fadeIn().text(errorText) ;
                    }
                }
                setTimeout(function() {
                    $('#ajaxErrorMessage').fadeOut("slow");
                }, 5000 );
                console.log(data.message)
                // more console logs here
            }
        })
    });
});

views.py

def create_item(request):
    # request is sent via ajax
    if request.is_ajax and request.method == "POST":
        form = ItemForm(request.POST)
        data = {}
        if form.is_valid():
            data = form.save()
            # serialize the new item object in json
            data = serializers.serialize('json', [data, ])
            # send data to the client side
            return JsonResponse({"data": data}, status=200)
        else:
            # raise form errors if there is any
            return JsonResponse(data=form.errors.as_json(escape_html=False), safe=False, status=400)
    form = ItemForm()
    return HttpResponse(data=form.errors.as_json(escape_html=False), safe=False, status=400)

【问题讨论】:

    标签: javascript django ajax ajaxform


    【解决方案1】:

    jQuery.ajax()的错误函数只接收三个参数(参考https://api.jquery.com/jquery.ajax/),即:

    jqXHR jqXHR, String textStatus, String errorThrown

    如果您想要从 ajax 调用返回的数据,您需要从 jqXHR 访问它:

    error: function (jqXHR, textStatus, errorText) {
        let data = jqXHR.responseJSON;
        // If above line does not work, might not since you don't specify `dataType: "json"` use below line
        // let data = $.parseJSON($xhr.responseText);
        // YOUR CODE HERE
    }
    

    【讨论】:

      猜你喜欢
      • 2021-01-01
      • 2023-01-10
      • 2017-07-29
      • 2020-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-07
      • 1970-01-01
      相关资源
      最近更新 更多