我有一个HTML文件,显示“PRESENT”一词。
当我点击该单词时,我想将AJAX请求发送到PHP文件,该文件在屏幕上和数据库中将单词更改为“ABSENT”。
有两个问题:
PHP永远不会回复HTML文件。如果确实如此,那么changeState()函数会发出一条警告“服务器已响应!”
即使调用了changeState()函数,PHP文件也从不执行SQL语句。如果是这样,数据库将被更新,而不是。
的index.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>
updateState.php
<?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
?>
答案 0 :(得分:0)
index.html
中存在语法错误 if(window.XMLHttprequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
“XMLHttprequest”应该用大写字母R拼写为“XMLHttpRequest”。
很抱歉让所有人感到困惑。