Ajax提交表单数据(包含文件)

1. 表单数据->JSON->后台

2. 表单序列化【方式一】

jquery.serializejson.js
<script src="/js/jquery.serializejson.js"></script>
<script>
    $('#btnRegister').click(function(){
        console.log(JSON.stringify($('#form1').serializeJSON()))
        $.ajax({
            type: 'post',
            url: '/loginPro',
            contentType:'application/json;charset=utf-8',
            async: true,
            //设置验证方式,设置请求头
            data: $('#form1').serializeJSON(),
            success: function (result) {
            },
            error: function () {
                console.log('error')
            }
        });
    })

</script>

 

3. 使用FormData类

//表单提交
var formData = new FormData($('#addUserForm')[0])
console.log(formData)
$.ajax({
    url:'/user/addPro.do',
    type:'post',
    data:formData,
    contentType: false, //必须
    processData: false, //必须
    success:function (result) {
        
    },error:function () {
       
    }
});

 

 

  在上面的js代码中,我们使用Jquery的ajax方法来提交数据。

  注意:应该使用较新的Jquery,老版本的可能不支持,同时必须设置contentType : false和processData : false。否则,jquery会报“Uncaught TypeError: Illegal invocation”这样的错误。因为jquery会试图将不是字符串的内容进行转换,设置processData : false禁止其转换,设置contentType : false是告诉jquery不要为其设置Content-Type头,防止上传失败。

  注意:对于springmvc的后台,需要配置视图解析器,否则文件为null:

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize">
            <value>102400</value>
        </property>
        <property name="defaultEncoding">
            <value>utf-8</value>
        </property>
    </bean>

 

 

 

4. string <-->Object

var str = '{"name":"admin","age":20}';
var obj = eval('('+str+')');  //方式一

//方式二,注意 JSON字符串的引号必须使用  "
 var obj = JSON.parse(str)
posted @ 2018-03-30 13:33  fight139  阅读(610)  评论(0编辑  收藏  举报