hurriedly% 2015-12-14 14:36 采纳率: 100%
浏览 28

基本的AJAX脚本不起作用

I'm trying to load a file and display it in the div section of my web page, using AJAX.
The console output shows that the XMLHttpRequest object is successfully created, but then nothing happens: the callback function is never called and the content of the URL is not fetched.

<body>
    <div id="demo"><p>Some text</p></div>
    <button type="button" onclick="loadDoc()">Request URL</button>
    <script>
        function loadDoc() {
            var xhttp;

            if (window.XMLHttpRequest) {
                xhttp = new XMLHttpRequest();
                console.log('object created'); // this message is printed
                } else if (window.ActiveXObject) {
                xhttp = new ActiveXObject("Mіcrosoft.XMLHTTP");
            }
            xhttp.onreadystatechange = function() {
                console.log('inside callback function'); // this message is never printed 
                if(xhttp.readyState == 4 && xhttp.status == 200) {
                    document.getElementById("demo").innerHTML = xhttp.responseText;
                }
                xhttp.open("GET", "http://tools.ietf.org/rfc/rfc6120.txt", true);
                xhttp.send(null);
            };
        }
        console.log('end of script'); // this message is printed
    </script>
</body>

I don't know much about HTTP requests and I'm assuming that AJAX can be used to load an url that is perfectly accessible to my web browser.
Is this assumption incorrect? If not, then what am I doing wrong?

  • 写回答

1条回答 默认 最新

  • weixin_33726943 2015-12-14 14:40
    关注

    Reorder your code

            xhttp.onreadystatechange = function() {
                console.log('inside callback function'); 
                if(xhttp.readyState == 4 && xhttp.status == 200) {
                    document.getElementById("demo").innerHTML = xhttp.responseText;
                }
            };
    
            xhttp.open("GET", "http://tools.ietf.org/rfc/rfc6120.txt", true);
            xhttp.send(null);
    

    You must to send the request and the callback will be fired automatically. If you put that code inside the callback, you never achieve the request to the txt file

    评论

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 如何将下列的“无限压缩存储器”设计出来
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口