雖然我對AJAX
很新,但我真的不知道爲什麼這樣做不能正常工作。我有一個可以通過點擊eventlistener進行編輯的表,然後有另一個事件監聽器監聽輸入鍵的按鍵,並在發生這種情況時獲得不同的變量並向服務器發送AJAX發佈請求。但是,當我按下Enter鍵時,什麼也沒有發生。什麼也沒有發生,我的意思是我留在我所在的頁面上,而不是服務器上的PHP函數將我指向其他地方。奇怪的是,在我ajax.send(vars)
後,我console.logged我的ajax
對象和響應顯示正在服務的HTML頁面,但:
1.它顯示了我會得到的響應,如果我的ID,loc或列值爲空(當我記錄這些變量時,他們不是)
2.該頁面沒有被提供。 ajax對象顯示響應,但我(最終用戶)沒有看到該響應。
這裏是我的JavaScript:
從AJAX/PHP獲得回覆
index.addEventListener("keypress", function(e){
var key = e.keyCode;
if (key === 13) {
var entry = e.path[0].innerText;
var tabID = e.path[1].id;
var table = tabID.charAt(0);
if (table === 'o') {
table = "otheraccounts";
} if (table === 'wh') {
table = "wheatstoneaccounts";
} if (table === 'wo') {
table = "wideorbitaccounts";
}
var ID = tabID.charAt(1);
var column = e.path[0].id;
var loc = e.path[3].getElementsByTagName("input").location.value;
var ajax = new XMLHttpRequest();
ajax.open("post", "../other/index.php?action=updateTable", true);
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajax.send(entry, table, ID, column, loc);
}
}, false)
這裏是PHP
:當它到達一個重定向頭
case 'updateTable':
$column = filter_input(INPUT_POST, 'column', FILTER_SANITIZE_STRING);
$ID = filter_input(INPUT_POST, 'ID', FILTER_SANITIZE_NUMBER_INT);
$table = filter_input(INPUT_POST, 'table', FILTER_SANITIZE_STRING);
$entry = filter_input(INPUT_POST, 'entry', FILTER_SANITIZE_STRING);
$location = filter_input(INPUT_POST, 'loc', FILTER_SANITIZE_STRING);
if (empty($ID) || empty($column) || empty($table)){
$message = "<p class='message'>Stop tampering with my IDs!!</p>";
$_SESSION['message'] = $message;
header("Location: /radiosite/other/index.php?action=$location");
exit;
}
$result = updateEntry($column, $ID, $table, $entry);
if ($result === 1) {
$message = "<p class='message'>The entry was successfully updated in the database</p>";
$_SESSION['message'] = $message;
header("Location: /radiosite/other/index.php?action=$location");
exit;
} else {
$message = "<p class='message'>Nothing was added to the database</p>";
$_SESSION['message'] = $message;
header("Location: /radiosite/other/index.php?action=$location");
exit;
}
break;
您沒有處理來自AJAX響應的回調函數。 'ajax.send(entry,table,ID,column,loc);'不是發送參數的正確方法。 – Barmar
您不能使用'header(「Location」)'在AJAX請求之後重定向。 – Barmar