为什么这个非常简单的 AJAX 脚本不起作用


Why is this very simple AJAX script not working

只是想做一个非常简单的AJAX,但什么都没有。谢谢!

<script>
function update()
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  var str='test';
xmlhttp.open("GET","localhost/userupdate.php?q="+str,true);
xmlhttp.send();
}
</script>

和 PHP 页面 localhost/userupdate.php (WAMP)

<?php
$q=$_GET["q"];
echo $q;
?>

首先,您应该在xmlhttp.open中使用完整的 URL -- http://localhost/userupdate.php 。如果userupdate.php文件与此脚本位于同一目录中,则只需改用userupdate.php即可。

其次,你没有对响应做任何事情。由于响应是字符串,因此可以使用responseText属性来检索它。

function update() {
    if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else { // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            console.log(xmlhttp.responseText);
        }
    }
    var str = 'test';
    xmlhttp.open("GET", "http://localhost/userupdate.php?q=" + str, true);
    xmlhttp.send();
}