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

Javascript 如何在ajax事件(onreadystatechange)上创建函数,javascript,ajax,Javascript,Ajax,我对ajax非常陌生。 试着通过 正在尝试的代码: <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

我对ajax非常陌生。 试着通过

正在尝试的代码:

<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>

AJAX
xmlhttp=新的XMLHttpRequest();
函数getScores(){
xmlhttp.onreadystatechange()=函数(){
if(xmlhttp.readyState==4&&xmlhttp.status==200){
document.getElementById('scores').innerHTML=xmlhttp.responseText;
}否则{
document.getElementById('scores').innerHTML=“Sonal Goyal”
}
}
open(“GET”https://www.learntoprogram.tv/baseball.php“,对);
xmlhttp.send();
}

我缺少的地方是什么?

您的代码在我看来很好,只是您输入的容器id中有拼写错误

要找出错误,请在您的else中输出xmlhttp数据 条款


首先用“score”替换“score”,或者用其他方式,在这里我得到输出:sonal goyal,但是我想要一些其他文本。这在我的文件中。这意味着在Ajax请求过程中出现了错误。在else子句中输出xmlhttp.readystate和xmlhttp.status。这将给我们一个错误的线索。顺便说一句,我建议你总是使用var来定义变量,即使它在没有变量的情况下工作。在这种特殊情况下,我将把xmlhttp定义放在函数中。这有助于避免污染全局范围。k您能告诉我Ajax与Json或Ajax与dojo都是sameJson是对象文字符号的子集,例如,可以用于以正确的形式转换php对象,以在JS中显示。要了解更多详细信息,只需谷歌一下。Dojo是一个小框架,它为Ajax请求提供了一些速记功能(不仅如此)。还有一个需要提到的是jQuery,它(我认为)是一个更大的框架,我发现它与Ajax一样,在很多方面都非常有用。
xmlhttp.onreadystatechange() = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById('scores').innerHTML = xmlhttp.responseText;
            } else {
                document.getElementById('scores').innerHTML = xmlhttp.status;
            }
        }