RequestError:无法在AJAX / DOJO中加载文件

时间:2014-07-01 16:14:26

标签: jquery ajax dojo

我在tomcat服务器的webapps文件夹中托管了一个名为hi.txt的文本文件。我可以在浏览器中访问该URL,但奇怪的是我的AJAX调用在下面的代码中显示文件内容不适用于同一个链接(//hostname:8080/dojo/hi.txt)。

我收到错误消息 RequestError:无法加载URL状态:0 。任何人都可以建议什么可以解决这个问题?我在DOJO中使用AJAX函数。

P.S:要查看以下代码中的错误,请将其复制到file_name.txt文件中,然后另存为file_name.html并在IE或Firefox中打开。

<!DOCTYPE HTML>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Demo: dojo/request/xhr</title>
        <link rel="stylesheet" href="http://dojotoolkit.org/documentation/tutorials/resources/style/style.css" media="screen">
        <link rel="stylesheet" href="http://dojotoolkit.org/documentation/tutorials/1.6/resources/style/demo.css" media="screen">
    </head>
    <body>
        <h1>Demo: dojo/request/xhr</h1>
        <p>Click the button below to see dojo/request/xhr in action.</p>
        <div>
            <button id="textButton">Request Text File</button>
        </div>
        <br /><br />
        <div id="resultDiv">
        </div>
        <!-- load dojo and provide config via data attribute -->
        <script src="http://ajax.googleapis.com/ajax/libs/dojo/1.8.5/dojo/dojo.js"></script>
        <script>
            require(["dojo/dom", "dojo/on", "dojo/request", "dojo/domReady!"],
                function(dom, on, request){
                    // Results will be displayed in resultDiv
                    var resultDiv = dom.byId("resultDiv");

                    // Attach the onclick event handler to the textButton
                    on(dom.byId('textButton'), "click", function(evt){
                        // Request the text file
                        request.get("http://localhost:8080/dojo/hi.txt").then(
                            function(response){
                                // Display the text file content
                                resultDiv.innerHTML = "<pre>" + response + "</pre>";
                            },
                            function(error){
                                // Display the error returned
                                resultDiv.innerHTML = "<div class=\"error\">" + error + "<div>";
                            }
                        );
                    });
                }
            );
        </script>
    </body>
</html>

1 个答案:

答案 0 :(得分:0)

您需要从here下载道场来源。并将文件置于相同级别,与本地tomcat服务器上的文件 h1.txt 一致。 然后在代码中更改以下行 从

<script src="http://ajax.googleapis.com/ajax/libs/dojo/1.8.5/dojo/dojo.js"></script>

要。

<script src="dojo/1.8.5/dojo/dojo.js"></script>

服务器上的目录结构应如下所示。

/index.html
/dojo/h1.txt
/dojo/1.8.5/dojo/<source files and subdirectories>
/dojo/1.8.5/dojox/<source files and subdirectories>
/dojo/1.8.5/dijit/<source files and subdirectories>