XMLHttprequest.send (null) my code failed

I am currently writing a search function using JavaScript.

However, when I try to test my creation, I find that it stops about halfway for some obvious reason.

Below is my code:

document.getElementById("test").innerHTML = ""; var Connect = new XMLHttpRequest(); Connect.open("GET", "xmlTest.xml", false); document.getElementById("test").innerHTML = "1"; Connect.send(null); document.getElementById("test").innerHTML = "2"; var docX = Connect.responseXML; var linjer = docX.getElementsByTagName("linjer"); 

The first line is to clear the potential error message from the code above. Then I try to open the XML file, since I need to read it.

As you can see, I introduced two debug statements there; they will print 1 or 2 depending on how far I get the code.

Using this, I found that it definitely stops at the Connect.send(null); statement Connect.send(null); (since 1 is printed, but 2 never works), but I cannot understand why. Google says it may be that chrome cannot access local files, but when I found a way to allow Chrome to do this, it still doesn't work.

What am I doing wrong?

+5
source share
1 answer

This could be a synchronous issue requiring an answer that your code just doesn't get.

Try using an asynchronous call instead:

 Connect.open("GET", "xmlTest.xml", true); 

Also, make sure you set up the correct callbacks, since now you will use async instead of synchronous code:

 // Global variable scope var docX; var linjer; // Define your get function getDoc = function(url, cbFunc) { var Connect = new XMLHttpRequest(); // Perform actions after request is sent // You'll insert your callback here Connect.onreadystatechange = function() { // 4 means request finished and response is ready if ( Connect.readyState == 4 ) { // Here is where you do the callback cbFunc(Connect.responseXML); } }; // 'true' param means async, it is also the default Connect.open('GET', url, true); Connect.send(); } // Define your callback function callbackFunction = function(responseXML) { // XML file can now be stored in the global variable window.docX = responseXML; window.linjer = window.docX.getElementsByTagName("linjer"); } // And here is the call you make to do this getDoc("xmlTest.xml", callbackFunction); 

To get a better understanding of all this, do some area research, closing , callbacks, and async .

+1
source

Source: https://habr.com/ru/post/1234530/


All Articles