虽然我对 AJAX
很陌生,但我真的不知道为什么它不能正常工作。我有一个通过单击事件监听器进行编辑的表,然后有另一个事件监听器监听 Enter 键的按键,当发生这种情况时,会获取不同的变量并向服务器发送 AJAX post 请求。但是,当我按 Enter 键时,什么也没有发生。所谓什么都没有发生,我的意思是我停留在我所在的页面上,而不是服务器上的 PHP 函数将我引导到其他地方。奇怪的是,在我的 ajax.send(vars)
之后,我 console.logged 出我的 ajax
对象,并且响应显示正在提供 HTML 页面,但是:
1.它显示了如果我的 ID、loc 或列值为空(当我注销这些变量时,它们不是空的)时我会得到的响应
2. 该页面未被提供。 ajax 对象显示了响应,但我(最终用户)没有看到该响应。
这是我的 JavaScript:
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 在获取重定向 header 时不会重定向浏览器。这只是告诉它转到该备用 URL 来获取响应数据。
更改 PHP,使其以字符串形式返回新 URL。更改行如下:
header("Location: /radiosite/other/index.php?action=$location");
至:
echo "/radiosite/other/index.php?action=$location";
然后,您可以在 Javascript 代码中读取响应并将其分配给 window.location
以执行重定向。
您也没有正确发送 POST 参数。您需要构造 URL 编码的字符串。
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=' + encodeURIComponent(entry) + '&table=' + encodeURIComponent(table) + '&ID=' + encodeURIComponent(ID) + '&column=' + encodeURIComponent(column) + '&loc=' + encodeURIComponent(loc));
ajax.onload = function() {
window.location = ajax.responseText.trim();
};
关于javascript - 从 AJAX/PHP 获取响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46009710/