Javascript 使用 jQuery 使用 multipart/form-data 进行 HTTP POST 调用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3537774/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Making an HTTP POST call with multipart/form-data using jQuery?
提问by Alex Brooks
I'm trying to make a HTTP POST call with multipart/form-data , using jQuery:
我正在尝试使用 jQuery 使用 multipart/form-data 进行 HTTP POST 调用:
$.ajax({
url: 'http://localhost:8080/dcs/rest',
type: 'POST',
contentType:'multipart/form-data',
data: 'dcs.source=boss-web&query=data&dcs.algorithm=lingo&dcs.output.format=JSON&dcs.clusters.only=true',
//dataType: "jsonP",
success: function(jsonData) {alert('POST alert'); data=jsonData ; },
error : function(XMLHttpRequest, textStatus, errorThrown) {
console.log('An Ajax error was thrown.');
console.log(XMLHttpRequest);
console.log(textStatus);
console.log(errorThrown);
}
});
It doesn't work. Firebug returns an undefined error and the returned XMLHttpRequstobject multipart field is set to false.
它不起作用。Firebug 返回一个未定义的错误,并且返回的XMLHttpRequst对象 multipart 字段设置为 false。
What can i do to make this work with jQuery? And if it's not possible is there a simple to achieve this?
我该怎么做才能使用 jQuery 完成这项工作?如果这是不可能的,是否有一个简单的方法可以实现这一目标?
i.e. idon't need to transfer files , just some data. but the server requires multipart.
即不需要传输文件,只需要传输一些数据。但服务器需要多部分。
回答by Darin Dimitrov
multipart/form-datadoesn't look at like this:
multipart/form-data看起来不像这样:
dcs.source=boss-web&query=data&dcs.algorithm=lingo&dcs.output.format=JSON&dcs.clusters.only=true
This is application/x-www-form-urlencoded.
这是application/x-www-form-urlencoded。
Here's an exampleof how multipart/form-datarequest looks like. And the related RFC 1867.
下面是一个例子,如何multipart/form-data要求样子。以及相关的RFC 1867。
multipart/form-datais quite often associated with uploading files. If this is your case you could take a look at the jquery form pluginwhich allows you to ajaxify forms and supports file uploadsas well.
multipart/form-data通常与上传文件有关。如果这是您的情况,您可以查看jquery 表单插件,它允许您对表单进行 ajaxify 并支持文件上传。
回答by NkS
回答by gilcierweb
This way works:
这种方式有效:
$( "form#upload-form" )
.attr( "enctype", "multipart/form-data" )
.attr( "encoding", "multipart/form-data" );
$.ajax({
type: "POST",
contentType:attr( "enctype", "multipart/form-data" ),
url: "/adm/oferta_insert",
data: dados,
success: function( data ) {
alert( data );
}
});

