derek5. 2017-03-31 12:09 采纳率: 100%
浏览 154

Ajax中的URL open()

This is my first Ajax program and I can't fix the code because I'm not sure where/what the problem is.

The error(which I'm unable to interpret) while using the debugger is, XMLHttpRequest cannot load http://localhost/function.txt. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

function calling()
{
    var x;
    if (window.XMLHttpRequest) {
    x = new XMLHttpRequest();
    } else {

    x = new ActiveXObject("Microsoft.XMLHTTP");
    }

    x.onreadystatechange = function(){
        if(this.readyState == 4 && this.status == 200)
        {
            document.getElementById("block").innerHTML = this.responseText;
        }

    };
    x.open("GET", "http://localhost/function.txt",true);
    x.send();
}

function.txt

<html>
<head></head>
<body>
<h2>Ajax is working</h2>
</body>
</html>
  • 写回答

3条回答 默认 最新

  • weixin_33686714 2017-03-31 12:15
    关注

    Is your js located at the same location as your function.txt?

    For more information about CORS, have a look at this link: https://www.html5rocks.com/en/tutorials/cors/

    UPDATE: This works for me, I think there is maybe something with your Apache settings...

    function calling()
    {
      var xhr = new XMLHttpRequest(),
          method = "GET",
          url = "function.txt";
    
      xhr.open(method, url, true);
      xhr.onreadystatechange = function () {
              if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
                  alert(xhr.responseText);
              }
          };
      xhr.send();
    }
    
    calling();
    
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?