所以我的网页上有一个按钮数组,用于通过读取带有 php/ajax 组合的文本文件来显示机器人的位置。该脚本将按钮设置为相同的颜色,然后更改按钮的颜色以显示我们机器人的位置。这是代码片段:
function position(){
setInterval(function(){ //wait function
document.getElementById("A").style.background ="#008000";
document.getElementById("B").style.background ="#008000";
document.getElementById("C").style.background ="#008000";
document.getElementById("D").style.background ="#008000";
var request = new XMLHttpRequest();
request.onreadystatechange = function(){
if (request.readyState == 4 && request.status == 200){
console.log(request.responseText);
if (request.responseText == 'A'){
document.getElementById("A").style.background ="#ff6600";
} else if (request.responseText == 'B'){
document.getElementById("B").style.background ="#ff6600";
} else if (request.responseText == 'C'){
document.getElementById("C").style.background ="#ff6600";
} else if (request.responseText == 'D'){
document.getElementById("D").style.background ="#ff6600";
} else if (request.responseText == 'E'){
document.getElementById("E").style.background ="#ff6600";
} else {
document.getElementById("A").style.background ="#ff6600";
}
}
}
request.open('POST', 'positionupdate.php', true); //script to read text file
request.send();
},3000);} //wait
所以,我知道 php 脚本正在运行,因为控制台日志显示文本文件中返回的字符正确。但是,我的脚本只是不处理字符并永久返回“else”条件。
有什么想法吗?
最佳答案
所以问题是我传递的是一个对象而不是一个值。在我的 php 脚本中,我能够通过使用 json_encode() 函数解决这个问题,并将一个工作程序组合在一起。
作为引用,我更新的 php 脚本:
<?php
$myfile = fopen("position.txt","r") or die("Unable to open file!");
$value = fread($myfile, filesize("position.txt"));
echo json_encode($value);
fclose($myfile);
?>
关于javascript - HTML - JavaScript 函数不处理 responseText,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49717643/