我想發送一個JavaScript變量來處理服務器端的PHP然後回顯結果。我的ajax請求結果爲readyState == 4
和status == 200
,但PHP仍然回顯空數組/值。從JavaScript到PHP的POST值通過AJAX無jQuery
我敢肯定,這是來自我的Ajax調用發送一個空請求,但我試過的一切都沒有工作,所以也許我會在這裏全錯了。
JS(從index.html
):
var valueToSend = Math.random();
var request = false;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
request = new ActiveXObject('Microsoft.XMLHTTP');
}
function send_ajax() {
if (request) {
request.open('POST', 'test.php', true);
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
console.log(request.responseText);
}
}
request.send(valueToSend); //this line is probably not sending the value the way I expect it to
}
}
PHP(從test.php
):
echo $_POST['name']; //simple echo to check if PHP indeed receives valueToSend
我的最後一次嘗試是改變request.send(valueToSend);
與.send(encodeURI('name=' + valueToSend));
,但它只是由Ajax調用重定向頁面位置到一個不存在的。
我在做什麼錯?
是通向test.php的正確WRT的文件,這是執行在? – ayushgp
只需雙重檢查:是的,它是正確的。 –