0

我有一些发送 ajax 请求的 javascript 代码,但我没有得到任何响应。我该如何解决这个问题?谢谢!

我试图获取的链接是: http ://research.engineering.wustl.edu/~todd/cse330/demo/lecture6/helloClass.txt

我的代码:

<!DOCTYPE html>
<html>
<head>
  <script type="text/javascript">    
  function sendRequest() {    
    alert("Sending request");    
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open("GET","http://research.engineering.wustl.edu/~todd/cse330/demo/lecture6/helloClass.txt",true);
    xmlHttp.addEventListener("load",ajaxCallback,false);
    xmlHttp.send(null);
  }

  function ajaxCallback(event) {
    alert("Here is the response " + event.target.responseText );
    document.getElementById("demo").innerHTML= event.target.responseText;
  }    
  </script>
  </head>
  <body>
    <h1>My Ajax  Web Page</h1>
    <p id="demo">I will display something here</p>    
    <form>
      <input name="submit" type=button value="Send Ajax Request" onClick="sendRequest()">
    </form>    
  </body>
</html> 

谢谢您的回答。我刚刚按照您的建议尝试了 JSONP,我使用

<script type="text/javascript" src="http://research.engineering.wustl.edu/~todd/cse330/demo/lecture6/helloClass.txt?jsonp=parseResponse"> 

对于我的新脚本标签,但仍然无法正常工作。任何进一步的提示?谢谢!

谢谢大家的回答!但我对这项技术很陌生,所以还是有点困惑。你介意带来更详细的代码供我学习吗?我对代理监听方法非常感兴趣。

4

2 回答 2

2

I assume that you are not writing this HTML on http://research.engineering.wustl.edu/. If so, then you have just had a brush with the Same Origin Policy, which disallows cross-domain requests.

Now there are ways to do this cross-domain communication, and some of the common ways are Cross-Origin Resource Sharing and JSONP. You can also make your server, the domain your page is living in, a proxy server which fetches the remote page for you, since server-code is not bound to SOP.

于 2013-07-20T00:33:32.997 回答
0

首先:您根本无法发出跨浏览器 ajax 请求。

JSON 可以工作,但需要对您的 javascript 进行一些重新编码。

解决方案:通过您的服务器中继请求。在您的服务器上创建一个代理来侦听以下请求:“/Relay?url= http://research.engineering.wustl.edu/~todd/cse330/demo/lecture6/helloClass.txt ”并以任何答案进行响应网址。您服务器上的编码很简单,并且需要在您的 javascript 中进行最少的重新设计。如果您对如何编写服务器代码有任何疑问,请尽管提问。

于 2013-07-20T01:23:52.477 回答