Modal dialog (solve upload file)

When implementing functions such as adding | modifying in a modal dialog box, when submitting form data using ajax, you must consider whether the form contains a file field.

Case 1: Do not include file fields

  follow $("#form's id").serialize() or .serializeArray() or form data

  and then use $.post();

var formdata = $("#form1").serializeArray
Alert(formdata) that cannot upload files
var url ="<%= request.getContextPath()%>/upload/demo1";
$.ajax({
url:url,
data:formdata, //name =zhangsan&age=50 {}
        contentType: false,//Default: "application/x-www-form-urlencoded"
        processData: false,//Set the processData option to false to prevent automatic conversion of data format
type:"post",
dataType: "json",
success:function(data){
alert(data);
},
error:

}
});


Case 2: Include file fields

  Practice 1: Use the new features provided by html5: FormData

    var formdata = new FormData(document.getElementById("form1"));//You can upload files

var url ="<%= request .getContextPath()%>/upload/demo1";
$.ajax({
url:url,
data:formdata, //name=zhangsan&age=50 {}
        contentType: false,//default: "application/x-www-form -urlencoded"
        processData: false,//Set the processData option to false to prevent automatic conversion of data format
type:"post",
dataType:"json",
success:function(data){
alert(data);
},
error:function( er){
alert(er.responseText);
}
});   Practice 2: Use the jquery.form.js plugin




        <script type="text/javascript" src="jquery-1.10.2.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>

var url ="<%= request.getContextPath()%>/upload/demo2";

$("#form1").ajaxSubmit({ 
            type:'post', 
            url:url, 
            clearForm:true,//Clear all form elements Value
            resetForm:true,//Reset the value of all form elements
            success:function(data){ 
                alert(data); 
            }, 
            error:function(XmlHttpRequest,textStatus,errorThrown){ 
                alert("Upload failed");
            } 
        } );

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326316676&siteId=291194637