07月12, 2017

$.ajax处理form-data的请求

简单记录一下。

相信很多都知道jquery发application/json的请求,代码是这样写的:

var params = {
    a: 1,
    b: 2
}
$.ajax ({
    url: "url",
    type: "POST",
    data: JSON.stringify(params),
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    success: function(data){
        // ...业务逻辑处理
    }
});

所以我下意识地以为,form-data的请求,可以这样书写:

var postData = new FormData();
postData.append("a", 1);
postData.append("b", 2);
$.ajax({
    url: "url",
    type: "post",
    dataType: "json",
    contentType: "multipart/form-data; charset=utf-8",
    data: postData
}).then(function(data) {
    // ...处理业务逻辑
})

结果报错了。。。

查了一下才知道,必须要这样写:

var postData = new FormData();
postData.append("a", 1);
postData.append("b", 2);
$.ajax({
    url: "url",
    type: "post",
    dataType: "json",
    processData: false,
    contentType: false,
    data: postData
}).then(function(data) {
    // ...处理业务逻辑
})

不同之处在于:

{
    processData: false,
    contentType: false
}

Setting processData to false lets you prevent jQuery from automatically transforming the data into a query string. See the docs for more info.

Setting the contentType to false is imperative, since otherwise jQuery will set it incorrectly.

这是出处的链接地址:How to send FormData objects with Ajax-requests in jQuery?

本文链接:www.my-fe.pub/post/jquery-ajax-form-data.html

-- EOF --

Comments

评论加载中...

注:如果长时间无法加载,请针对 disq.us | disquscdn.com | disqus.com 启用代理。