2014-02-11 26 views
2

我非常新的ajax。 试图通过tutorial如何在ajax事件上创建函数(onreadystatechange)

试图代码来理解:

<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

首先取代“分数”与“分”或周围的其他方法 – Manu

回答

2

你的代码对我来说看起来很好,除了你在input-divContainer id中有一个拼写错误。

要找出什么是你其他 子句中的错误输出XMLHTTP数据

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

这里我得到的输出:SONAL戈亚尔而是我想要一些其他的文字。这是我的文件。 – sonalgoyal

+0

这意味着您在Ajax请求期间发生了错误。在你的else子句中输出xmlhttp.readystate和xmlhttp.status。这会给我们一些线索,出了什么问题。 – Martin

+0

顺便说一句,我建议你总是使用var来定义变量,即使它没有工作。在这种特殊情况下,我会将xmlhttp定义放入函数中。这对于不污染全球范围是有益的。 – Martin

相关问题