私はw3schoolsでPHP/AJAXチュートリアルをフォローしていますが、スクエア1で少し障害にぶつかりました。この関数を呼び出すたびに、readystateは常に未定義です。
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
}
var xmlhttp;
if (window.XMLHttpRequest) {
console.log("Using XMLHttpRequest");
xmlhttp = new XMLHttpRequest();
}
else {
console.log("Using ActiveXObject");
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "gethint.php?q=" + str, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
console.log(xmlhttp.readystate);
if (xmlhttp.readystate == 4 && xmlhttp.status == 200) {
console.log(xmlhttp.status);
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
}
この行を変更した場合:
if (xmlhttp.readystate == 4 && xmlhttp.status == 200) { ...
これに(タイプミスを介して):
if (xmlhttp.readystate = 4 && xmlhttp.status == 200) { ...
それで動作しますが、このようなコードを書いているのは「魔法がここで起こる」ようなもののように感じます。