2013-03-31 45 views
0

我刚刚开始在W3Schools网站上学习ajax。在Try it editor on W3Schools.com页面上,当我尝试下面的代码时,我得到了正确的响应,正如人们可以从代码中期望的那样。您也可以尝试将代码复制并粘贴到给定链接页面的“提交代码”,单击“更改内容”按钮响应。非常简单的ajax XmlHttpRequest代码不要开玩笑

<!DOCTYPE html> 
    <html> 
     <head> 
      <script> 
       function loadXMLDoc() 
       { 
        var xmlhttp; 
        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==0) 
         { 
          document.getElementById("myDiv").innerHTML="0: request not initialized"; 
         }if (xmlhttp.readyState==1) 
         { 
          document.getElementById("myDiv").innerHTML="Server connection establish"; 

         }if (xmlhttp.readyState==2) 
         { 
          document.getElementById("myDiv").innerHTML="Request has been sent"; 
         }if (xmlhttp.readyState==3) 
         { 
          document.getElementById("myDiv").innerHTML="Server is processing the request"; 
         } 
         if (xmlhttp.readyState==4 && xmlhttp.status==200) 
         { 
          document.getElementById("myDiv").innerHTML=xmlhttp.responseText; 
         } 
        } 
        xmlhttp.open("GET","http://www.w3schools.com/ajax/ajax_example.asp",true); 
        xmlhttp.send(); 
       } 
      </script> 
     </head> 
     <body> 

      <div id="myDiv"><h2>Let AJAX change this text</h2></div> 
      <button type="button" onclick="loadXMLDoc()">Change Content</button> 

     </body> 
    </html> 

但是当我尝试相同的代码在我自己的HTML文件,然后单击“更改内容”按钮,我得到的角逐顺序改变(请ingnore类型错误)

  • 服务器连接已建立
  • 请求已发送。

之后什么也没有发生。我连接到互联网,也能够打开浏览器(Firefox)中的链接。我该怎么办?

+3

[同源策略](https://developer.mozilla.org/en-US/docs/JavaScript/Same_origin_policy_for_JavaScript) – Musa

回答

0

您不能使用从本地html文件中编写的代码使用ajax来访问另一个域地址。跨域ajax请求要求您使用jsonp来访问该数据。

在第一个例子中,由于您在制作ajax请求时已经在w3schools域中,因此它将起作用。

+0

thanx redDevil为您的快速响应。 – stackOverflow