2015-10-15 61 views
1

我正在處理某些事情,並且我有一個非常奇怪的問題。我提出一個AJAX請求像以下:AJAX請求提交,但不接收POST值

x = new XMLHttpRequest(); 
x.open('POST', url, true); 
x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); 
x.onload = function(){ 
    console.log(x.responseText); 
}; 
x.send(data); 

的問題是,當我提交請求時,PHP沒有收到POST值。該data變量看起來像以下:

Object { wordtype: "noun", word: "computer" } 

而且PHP像以下:

if(!isset($_POST['wordtype']) || !isset($_POST['word'])){ 
    echo "error 1"; 
    exit; 
} else { 
    $wordlist = json_decode(file_get_contents("words.json"), true); 
    $wordlist[$_POST['word']] = $_POST['wordtype']; 
    file_put_contents("words.json", json_encode($wordlist)); 
    echo "success"; 
} 

x.responseText值總是error 1;

謝謝
雅克·瑪萊

+0

你的意思是使用'onreadystatechange',而不是'onload'?你也應該使用'application/json' Content-Type並在你發送的對象上使用'JSON.stringify'。 –

+0

@RalphWiggum http://stackoverflow.com/a/14946525/5305938 –

回答

1

這個例子的工作原理:

var http = new XMLHttpRequest(); 
var url = "ajax.php"; 
var params = "wordtype=noun&word=computer"; 
http.open("POST", url, true); 

//Send the proper header information along with the request 
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
http.setRequestHeader("Content-length", params.length); 
http.setRequestHeader("Connection", "close"); 

http.onreadystatechange = function() {//Call a function when the state changes. 
    if(http.readyState == 4 && http.status == 200) { 
     alert(http.responseText); 
    } 
} 
http.send(params); 
+0

非常感謝。我認爲問題在於我使用對象作爲數據發送而不是參數字符串,並且發送了錯誤的標題。 –