ajax post 提交数据和文件

方式一:常用的方式是通过form.serialize()获取表单数据,但是,这样有个弊端,文件不能上传

            $.ajax({
                url:'/communication/u/',
                type:'POST',
                data:$('#form').serialize(),
                success:function(res){
                    ret = JSON.parse(res)
                    for (i in ret.error){
                        $("#er_"+i).html(ret.error[i][0].message)
                    }
                }
        })

方式二:

  使用FormData对象,用来封装数据,能够提交文件

具体请看:https://developer.mozilla.org/zh-CN/docs/Web/API/FormData/Using_FormData_Objects

   var formdata = new FormData(document.getElementById("modify"))         
   $.ajax({
                url:'/communication/u/',
                type:'POST',
                data:formdata,
                async: false, //不使用异步
          cache:false,//不缓存 processData:
false,//jquery不去处理发送的数据 contentType:false,//jQuery不去设置content-type请求头 success:function(res){ ret = JSON.parse(res) for (i in ret.error){ $("#er_"+i).html(ret.error[i][0].message) } } })

猜你喜欢

转载自www.cnblogs.com/wbdream/p/10475175.html