简体   繁体   中英

XMLHttpRequest has an invalid context error

this is my code:

<body><button onclick="myFunction()">Click me</button>
<script>
function readTextFile(file, callback) {
   var rawFile = new XMLHttpRequest();
   rawFile.overrideMimeType("application/json");
   rawFile.open("GET", file, false);
   rawFile.onreadystatechange = function() {
       if (rawFile.readyState === 4 && rawFile.status == "200") {
           callback(rawFile.responseText);
       }
   }
rawFile.send(null);
}

function myFunction(){
  document.write("<div id='cy'></div>");
  readTextFile("book.json", function(text){
        var data = JSON.parse(text);
        console.log("Something");
  }
}
</script>
</body>

This gives me the error:

XMLHttpRequest has an invalid context

But if i comment document.write("<div id='cy'></div>"); it works. Someone knows why?

在已加载的文档中调用document.write (隐式称为document.open ,这会破坏当前文档(XHR对象所属的上下文)并创建一个新文档。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM