2014-06-22 9 views
-1

这是我制作XHR请求的第一个代码,试图调试它,但无法找到故障所在。 我正在使用谷歌浏览器和wamp服务器。我正在使用的URL是我自己的计算机中的HTML文件此代码对于XHR有什么问题?

对于帮助我解决问题的麻烦,我感到抱歉。 我期待什么结果?

我希望我的浏览器会opent本地主机/ CSS /边距/ margin.html

但是,什么情况是,页面只是一片空白,当我点击“点击我!”。

<!DOCTYPE html> 
<html lang="en"> 
<head> 
     <meta charset="UTF-8"> 
    <title>Project 1</title> 
    <script type="text/javascript"> 
     var a; //Creating an object for the request named "a" 
     if(window.XMLHttpRequest) 
     { 
      a = new XMLHttpRequest(); 

     } 
     else if(window.ActiveXObject) 
     { 
      a= new ActiveXobject("Microsoft.XMLHTTP"); 
     } 
     function response() //This is the function that I would use as callback function 
     { 
      if(a.readyState==4) 
      { 
       if(a.status==200) 
       { 
        alert("perfect"); 
       } 
       else 
       { 
        alert("Getting improper response"); 
       } 
      } 
      else 
      { 
       alert("Not getting response"); 
      } 
     } 
     function open() //Making the request 
     { 
      a.open('GET', "localhost/CSS/Margins/margin.html", true); 
      a.onreadystatechange = response; 
      a.send(null); 
     } 


    </script> 
    <span onclick="open();">Click me!</span> //This onclick event would call the function that would make the request. 
</head> 
<body> 

</body> 
</html> 
+0

由于您没有解释您期望得到的结果,究竟是什么问题以及未提供任何上下文信息,因此无法帮助您。 –

回答

0

感谢您的帮助。

我正在犯的主要错误是打开函数的名称。这是一个关键字。 一旦我改变它,浏览器开始响应警报框。

我很感谢您的帮助。

PS-我使用:

a.open( “GET”, “//localhost/CSS/Margins/margin.html”,TRUE);

0

您的代码很好,但您输入的URL不是全局的,而是指向当前页面的相对路径。

更改为a.open('GET', location.protocol+"//localhost/CSS/Margins/margin.html", true);

+0

location.protocol +“// localhost”必须是url。 location.protocol给出“http:” – Jebin

+0

*“你输入的URL不是全局的,而是指向当前页面的相对路径”*使用相对URL有什么问题? –

+0

相对URL很好,但是由于他想使用本地主机作为主机,该代码并不适用于他。 – Rliger