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

Javascript 当XHR的asnyc参数设置为TRUE时,不返回任何内容,javascript,ajax,xmlhttprequest,Javascript,Ajax,Xmlhttprequest,当我尝试编写一个简单的代码来测试XMLHttpRequest函数时,我使用了以下代码: <script> //Global variable to store the XMLHttpRequest object var myRequest; //Package the request into its own function function getData() { //Feature-testing technique to ma

当我尝试编写一个简单的代码来测试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时,它就工作了


为什么???

xmlhttp指向本地文件的请求无法开箱即用

getData方法应该包含如下内容:

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

当您执行请求同步时,它工作的原因是您可能没有包含上述代码。

FYI,您应该使用window.onload=getData;。您希望传递函数引用,而不是立即执行函数的返回结果。这没有意义。getData正在启动一个ajax调用,然后将ReadyStateChange连接到getData,这将启动另一个ajax调用,等等。。。。如果某件事没有引起错误,这种情况将永远持续下去。您必须向我们展示实际使用ajax调用结果的代码,因为这可能就是您的编码错误所在,但您没有考虑到这一点。@jfriend00。你现在能给我一个解决方案吗?在你的问题中没有任何代码真正试图对ajax结果做任何事情。正如我之前所说的,我们需要查看该代码。请解释什么是requestObject requestObject参数是您的requestObject。XMLHttpRequest有4种状态。您必须等待执行代码,直到您的请求到达readyState 4,这意味着请求已完成。如果我只使用getData会怎么样?如果没有:requestobject,请看一下我的代码:这是可行的,应该很容易理解。祝你好运