Javascript XHR发送多部分/表单数据 [英] Javascript XHR send multipart/form-data
问题描述
我正在尝试发送多部分/表单数据内容类型请求:
I'm trying to send a multipart/form-data content-type request:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState==4){
alert(xhr.responseText);
}
}
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type","multipart/form-data; boundary=---------------------------275932272513031");
xhr.send('-----------------------------275932272513031 Content-Disposition: form-data; name="name"
test
----------------------------275932272513031--');
然后在php中,我只打印$_POST
数组
Then in php I just print the $_POST
array
print_r($_POST);
但是我每次都会得到一个空数组.我希望看到
But I get an empty array each time. I expect to see
Array (
name => "test"
)
我在做什么错了?
推荐答案
您的代码失败,因为您使用"Enter"代替了转义的换行符(\n
).
JavaScript不支持"first line[Enter]second line"
.如果需要带换行符的字符串,请使用"first line\nsecond line"
.
Your code failed because you've used "Enter" instead of an escaped line break character (\n
).
JavaScript doesn't support "first line[Enter]second line"
. If you need a string with a line break, use "first line\nsecond line"
.
解决此问题后,您的代码应该可以按预期工作(需要注意的是,请注意最后的注释):
Once you've fixed this problem, your code should work as intended (with one caveat, see final note):
var xhr = new XMLHttpRequest();
xhr.onload = function() {
alert(xhr.responseText);
};
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type","multipart/form-data; boundary=---------------------------275932272513031");
xhr.send('-----------------------------275932272513031\n' +
'Content-Disposition: form-data; name="name"\n\n' +
'test\n\n' +
'----------------------------275932272513031--');
注意:您的代码仅适用于包含UTF-8字符(不能二进制数据)的有效负载.如果您想了解有关通过XMLHttpRequest提交带有二进制数据的表单的更多信息,请参见
NOTE: Your code will only work for payloads that consists of UTF-8 characters, not binary data. If you want to learn more about submitting forms with binary data via XMLHttpRequest, see this answer and its linked references.
这篇关于Javascript XHR发送多部分/表单数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!