[英]ajax php javascript : error when using POST method
我在google上搜索過,關於stackoverflow的這個話題有很多問題。 例如“數據不是通過郵寄方法發送”等等。但似乎不是我的問題
案件與其他問題幾乎相同。 這些是錯誤消息:
Firefox(第21版):
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(第27版):
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.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
在你打電話給xhr.open
opts.data
應該是包含鍵/值對的字符串。 例如key=value&method=post
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.