[英]Why isn't the PHP file responding to my AJAX request?
我有一个显示“PRESENT”一词的 HTML 文件。
当我点击这个词时,我想向 PHP 文件发送 AJAX 请求,它在屏幕和数据库中将这个词更改为“不存在”。
有两个问题:
PHP 从不响应 HTML 文件。 如果是这样,changeState() 函数会发出警报,说“服务器已响应!”
即使调用了 changeState() 函数,PHP 文件也永远不会执行 SQL 语句。 如果是这样,数据库就会被更新,而事实并非如此。
索引.html
<html>
<head>
<title>Attendance System</title>
</head>
<body>
<div id="1">
<span onclick="changeState(this)">PRESENT</span>
</div>
<script>
function changeState(elem) {
var oldValue = elem.innerHTML;
var newvalue;
var itemID = elem.parentNode.getAttribute('id');
if (oldValue == 'PRESENT') {
newvalue = 'ABSENT';
} else {
newvalue = 'PRESENT';
}
alert("new value is " + newvalue + ", itemID is " + itemID);
var xmlhttp;
if(window.XMLHttprequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
alert("Server has responded!");
elem.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "updateState.php?newValue=" + newvalue + "&id=" + itemID, true);
xmlhttp.send();
}
</script>
</body>
</html>
更新状态文件
<?php
// Login procedure code here...
// I tried to substitute this palce with fixed dummy values before and it successfully updated the database. But the code doesn't work when it is like this.
$value = $_GET['newValue'];
$id = $_GET['id'];
// Construct SQL query
$query = "UPDATE attendanceList SET attendOrNot = '$value' WHERE id = '$id'";
// Execute SQL query
mysqli_query($conn, $query) or die('Query execution failed! ' . mysqli_error($conn));
// Print result text
print $value
?>
index.html 中存在语法错误
if(window.XMLHttprequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
“XMLHttprequest”应该拼写为“XMLHttpRequest”,并带有大写字母 R。
抱歉让大家混淆了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.