javascript 通过 JS 中的 XMLHttpRequest 对象发布表单数据?(跨浏览器)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8286934/
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
Post formdata via XMLHttpRequest object in JS ? ( cross browser)
提问by Royi Namir
Im trying to post a form data in js :
我试图在 js 中发布表单数据:
I have this code :
我有这个代码:
var formData = new FormData();
formData.append("username", "Groucho");
formData.append("accountnum", 123456);
formData.append("afile", "2");
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://xxxxx/xx.ashx",true);
xhr.send(formData);
Formdata according MDNis not available in IE ( or unknown).
根据MDN 的Formdata在 IE 中不可用(或未知)。
When I try this in FF:
当我在FF 中尝试此操作时:
( i think its fine...).
(我觉得还好……)。
when I try in IE:
当我在IE 中尝试时:
Whatis the solution to post form data ( or my data but in objective way) CROSSBROWSER ?
发布表单数据(或我的数据,但以客观方式)CROSSBROWSER 的解决方案是什么?
采纳答案by BlueSix
You didn't say which version of IE you're using. The formData object is not supported in IE9 or lower. XMLHTTPRequest2 (which contains the formData object) should be supported in IE10 (http://caniuse.com/xhr2)
你没有说你使用的是哪个版本的IE。IE9 或更低版本不支持 formData 对象。IE10 ( http://caniuse.com/xhr2)应支持 XMLHTTPRequest2(包含 formData 对象)
Cross-browser AJAX file upload is very hard to do right now. You couldtry building your own form header/boundaries in Javascript (see answer here: XMLHttpRequest POST multipart/form-data) but, personally, I don't believe it is worth the effort.
跨浏览器 AJAX 文件上传现在很难做到。您可以尝试在 Javascript 中构建自己的表单标题/边界(请参阅此处的答案:XMLHttpRequest POST multipart/form-data),但就个人而言,我认为这不值得付出努力。
回答by Sam Grondahl
I wrote a simple wrapper that you can use to send FormData in IE (and it won't mess up anything in webkit/gecko either). Simply include the following js before you try to use FormData:
我写了一个简单的包装器,你可以用它在 IE 中发送 FormData(它也不会在 webkit/gecko 中弄乱任何东西)。在尝试使用 FormData 之前,只需包含以下 js:
var ieFormData = function ieFormData(){
if(window.FormData == undefined)
{
this.processData = true;
this.contentType = 'application/x-www-form-urlencoded';
this.append = function(name, value) {
this[name] = value == undefined ? "" : value;
return true;
}
}
else
{
var formdata = new FormData();
formdata.processData = false;
formdata.contentType = false;
return formdata;
}
}
}
Now simply switch all new FormData() calls to new ieFormData(), and switch
现在只需将所有新的 FormData() 调用切换到新的 ieFormData(),然后切换
processData: false,
contentType: false,
to
到
processData: formdata.processData,
contentType: formdata.contentType,
cache: false,
and you're all set. Of course, this won't allow you to include files (you still need the iframe hack), but it will allow you to mimic FormData in IE.
你已经准备好了。当然,这不允许您包含文件(您仍然需要 iframe hack),但它允许您在 IE 中模拟 FormData。