Ajax成功后不会触发

问题描述 投票:0回答:1

在提交表单时,我想向用户提供反馈,说明ajax已经成功执行。我的ajax如下。

  $(function() {
            $('#submit').click(function (e) {
                var url = "{{ url_for('handle_data') }}"; // send the form data here.
                var form_data = new FormData($('#mainform')[0]);
                $.ajax({
                    type: "POST",
                    url: url,
                    data: form_data, // serializes the form's elements.
                    success: function () {
                        alert('success!!');
                    }
                });
                 e.preventDefault(); // block the traditional submission of the form.
            });

             // Inject our CSRF token into our AJAX request.
            $.ajaxSetup({
                beforeSend: function(xhr, settings) {
                    if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) {
                        xhr.setRequestHeader("X-CSRFToken", "{{ form.csrf_token._value() }}")
                    }
                }
            });
        });

而在后台,我的flask是:

@app.route('/handle_date', methods=['GET', 'POST'])
def handle_data():
    """
    :return:
    """
    print("hi there")
    return ""

我从来没有得到成功的提示信息。

html jquery ajax
1个回答
0
投票

服务器接收的不是JSON,而是一个FormData。而jQuery要想发送FormData,它需要

$.ajax({
    type: "POST",
    url: url,
    data: formData,

    // these three additional parameters
    processData: false,
    contentType: false,
    dataType: "json"
})

我做的第二个编辑是在后台,当从flask返回一个响应时,我必须将它包裹在jsonify下,以便ajax成功触发。

© www.soinside.com 2019 - 2024. All rights reserved.