AJAX不发布多字段表单

时间:2017-08-03 20:42:44

标签: javascript ajax flask wtforms

我正在尝试使用具有多个字段的单个表单,包括从Flask-WTForms填充的FileField。发布表单时,它不包含任何数据。如果不包含<form class="form-horizontal" enctype="multipart/form-data"> <div class="form-group"> <label class="col-sm-2 control-label">Material Description</label> <div class="col-sm-10"> {{ form2.description(placeholder='Material Description', class='form-control') }} </div> </div> <div class="form-group"> <label class="col-sm-2 control-label">Cost</label> <div class="col-sm-10"> {{ form2.cost(placeholder='Cost', class='form-control') }} </div> </div> <div class="form-group"> <label class="col-sm-2 control-label">Quantity</label> <div class="col-sm-10"> {{ form2.quantity(placeholder='Quantity', class='form-control') }} </div> </div> <div class="form-group"> <label class="col-sm-2 control-label">Used</label> <div class="col-sm-10"> {{ form2.used(placeholder='Used', class='form-control') }} </div> </div> <div class="form-group"> <label class="col-sm-2 control-label">Supplier</label> <div class="col-sm-10"> {{ form2.supplier(class='form-control') }} </div> <div class="form-group"> <label class="col-sm-2 control-label">Attachment</label> <div class="col-sm-10"> {{ form2.attachment(class='form-control') }} </div> </div> {{ form1.hidden_tag() }} <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button id="materialsButton" type="submit" class="btn btn-default">Add Materials</button> </div> </div> </form> ,则表单有效。 (它在提交常规字段之前有效,但是现在我一整天都在尝试添加文件上传但没有成功。)

我的表格如下:

@app.route('/api/submit_materials', methods=['POST'])
    def submit_materials_api():
    form = MaterialsForm()
    form.workorder_id.choices = [(work.id, work.id) for work in Workorder.query.order_by(desc('id'))]
    if form.validate_on_submit():
        workorder_id = form.workorder_id.data
        workorder = Workorder.query.filter_by(id = workorder_id).first_or_404()
        description = form.description.data
        cost = form.cost.data
        quantity = form.quantity.data
        used = form.used.data
        supplier = form.supplier.data
        attachment_filename = secure_filename(form.attachment.file.filename)
        form.attachment.file.save('static/attachments/' + str(workorder_id) + '_' + attachment_filename)
        materials = Materials(description, cost, quantity, used, supplier, attachment_filename)
        workorder.work_order_materials.append(materials)
        db.session.add(materials)
        db.session.commit()
        return jsonify({'materials' : materials.description, 'workorder_id' : workorder_id, 'quantity' : quantity})
    else:
        for field, errors in form.errors.items():
            for error in errors:
                error_data = (u"Error in the %s field - %s" % (getattr(form, field).label.text, error))
    return jsonify({'error' : error_data})

我的端点处理程序:

$('#materialsButton').click(function (e) {
                var form_data = new FormData($('#attachment')[0]);
                $.ajax({
                    type : "POST",
                    dataType :"json",
                    url : "/api/submit_materials",
                    data : { 
                            workorder_id : data.workorder_id,
                            description : $('#description').val(),
                            cost : $('#cost').val(),
                            quantity : $('#quantity').val(),
                            used : $('#used').val(),
                            supplier : $('#supplier').val(),
                            attachment : form_data,
                    },
                    contentType : false,
                    cache : false,
                    processData : false,
                    success: function (data) {
                        if (data.error) {
                        $("#errorAlert").text(data.error).show();
                        $("#successAlert").hide();
                        }
                     else {
                        $("#successAlert").text(data.quantity + ' of ' + data.materials + ' successfully added to workorder MCI' + data.workorder_id + '. You may submit additional materials or hours below.').show();
                        $("#errorAlert").hide();
                        $("#materialsForm").trigger("reset");
                        $("#hoursForm").fadeIn("slow");
                     }
                    }
                });
                e.preventDefault();

而我认为是罪魁祸首,我的JS / jQuery:

(".*),(.*")

为了节省空间,这只是整个JS脚本的一部分。

2 个答案:

答案 0 :(得分:1)

在ajax请求中使用formdata对象时,数据字段必须是formdata对象。

            $.ajax({
                ...
                data : form_data,
                ...
            });

此外,formdata构造函数采用的形式不是字段

var form_data = new FormData(this.form);

这会将表单中的所有字段添加到formdata对象中,然后将append()用于其余数据

form_data.append('workorder_id', data.workorder_id);

答案 1 :(得分:0)

你必须在发送到服务器端之前序列化formData。为表单设置ID。

<form class="form-horizontal" enctype="multipart/form-data" id="matarialsForm">

然后使用这个jquery。

$('#materialsButton').click(function (e) {
    e.preventDefault();
    var formData = new FormData();
    var stringData = $('#matarialsForm form').serializeArray();
    $.each(stringData,function(key,input){
            formData.append(input.name,input.value);
    });
                $.ajax({
                    type : "POST",
                    dataType :"json",
                    url : "/api/submit_materials",
                    data : formData
                    contentType : false,
                    cache : false,
                    processData : false,
                    success: function (data) {
                        if (data.error) {
                        $("#errorAlert").text(data.error).show();
                        $("#successAlert").hide();
                        }
                     else {
                        $("#successAlert").text(data.quantity + ' of ' + data.materials + ' successfully added to workorder MCI' + data.workorder_id + '. You may submit additional materials or hours below.').show();
                        $("#errorAlert").hide();
                        $("#materialsForm").trigger("reset");
                        $("#hoursForm").fadeIn("slow");
                     }
                    }
                });