当 XHR 的 asnyc 参数设置为 TRUE 时,不会返回任何内容



当我尝试一个简单的代码来测试XMLHttpRequest()函数时,我使用了以下代码:

<script>
//Global variable to store the XMLHttpRequest object
    var myRequest;
    //Package the request into its own function
    function getData()
    {
    //Feature-testing technique to make sure the browser
    //supports the XMLHttpRequest object
    if (window.XMLHttpRequest)
    {
    //create a new instance of the object
    myRequest = new XMLHttpRequest();
    }
    //else - the XMLHttpRequest object is not supported:
    //create an instance of ActiveXObject
    else
    {
    myRequest = new ActiveXObject("Microsoft.XMLHTTP");
    }
    //Use the open(retrievalMethod, "myDataFile.txt", bool) method
    myRequest.open("GET", "test.txt", true);
    //Use send() with a null argument - we have nothing to send:
    myRequest.send(null);
    //attach a function to handle onreadystatechange,
    //that is, the response from the server:
    myRequest.onreadystatechange = getData;
    alert(myRequest.responseText);
    }
</script>

我想简单地返回我的"test.txt"文件的内容。

现在当我运行此代码时,我什么也得不到!我只看到一个空白的屏幕.....

现在当我将 Asnyc 参数设置为 false 时,它有效!

为什么??

指向

本地文件的XMLHttpRequests不可能开箱即用(xmlhttpRequest for Local files)。

你的getData()方法应该包含这样的东西:

funtion getData (requestObject) {
    if (request.readyState === 4) {
         //DO STUFF
    }
}

执行请求同步时它之所以有效,是因为您可能没有包含上述代码。

最新更新