如何在ajax事件上创建函数(onreadystatechange)

时间:2014-02-11 13:06:38

标签: javascript ajax

我非常喜欢ajax。 试图通过tutorial

了解

尝试代码:

<DOCTYPE html PUBLIC" ..//w3c//DTDXHTML 1.0 strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>ajax</title>
<script language="javascript" type="text/javascript">
    xmlhttp = new XMLHttpRequest();
    function getScores() {
        xmlhttp.onreadystatechange() = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById('scores').innerHTML = xmlhttp.responseText;
            } else {
                document.getElementById('scores').innerHTML = "<strong>Sonal Goyal</strong>"
            }
        }
        xmlhttp.open("GET", "https://www.learntoprogram.tv/baseball.php", true);

        xmlhttp.send();
    }
</script>
</head>
<body>
    <div id="score"></div>
    <input type="button" value="get scores!" onclick="getScores()" />
</body>
</html>

我缺少的地方?

1 个答案:

答案 0 :(得分:2)

您的代码对我来说很好,除非您在input-divContainer id中有拼写错误。

找出你的else中的错误输出xmlhttp数据是什么 条款

xmlhttp.onreadystatechange() = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById('scores').innerHTML = xmlhttp.responseText;
            } else {
                document.getElementById('scores').innerHTML = xmlhttp.status;
            }
        }