我在 google 上搜索了一下,stackoverflow 上有很多关于这个主题的问题。例如“数据未通过 post 方法发送”等。 但似乎没有回答我的问题
案例与其他问题几乎相同。这些是错误信息:
火狐(v21):
InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable.
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
Chrome(v27):
Uncaught Error: InvalidStateError: DOM Exception 11
GET
发送请求时,没有错误。并且所有的GET数据都接收的很好。
但是当通过POST
+ setRequestHeader
发送时,itu会出现如上错误。当 setRequestHeader
被移除时,错误就消失了。没有错误,但是没有收到 POST 数据。我 print_r($_POST)
;那么数组为空
问题已更新。这是来电者:
goServer({
url : 'users/sign-in.php',
method : 'POST',
data : 'randomId=' + randomId + '&name=' + name + '&password=' + password,
done : function(response) {
alert(response);
},
fail : function(response) {
alert(response);
}
});
这是功能(抱歉,长线):
function randomString() {
var str = new Date().getTime(),
str2 = Math.random();
str = str.toString();
str2 = str2.toString();
str2 = str2.substring(2,7);
str += str2;
return str;
}
function goServer(opts) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = requestComplete;
function requestComplete() {
if ( xhr.readyState === 4 ) {
if ( xhr.status === 200 ) {
opts.done(xhr.responseText);
} else {
opts.fail(xhr.responseText);
}
}
}
if ( !opts.method || opts.method === undefined ) {
opts.method = "GET";
}
if ( !opts.cache || opts.cache === undefined ) {
opts.cache = false;
}
if ( opts.cache === false ) {
opts.url += '?nocache=' + randomString();
} else {
opts.url += '?nocache=false';
}
if ( opts.method === "GET" ) {
if ( opts.data !== '' && opts.data !== undefined ) {
opts.url += '&' + opts.data;
}
opts.data = '';
} else {
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
}
xhr.open(opts.method, opts.url, true);
xhr.send(opts.data);
}
请注意,数据参数(opts.data)在通过 GET 发送时设置为 url。当通过 POST 发送时,参数设置为 xhr.send(opts.data);
问题:如何正确获取POST数据?
谢谢
最佳答案
在调用 xhr.open
之后调用 xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
此外,opts.data
应该是包含键/值对的字符串。例如key=value&method=post
关于php - Ajax PHP JavaScript : error when using POST method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17182816/