0

I am trying to parse XML document from java script with the below code

var xhr = new XMLHttpRequest();
 xhr.onreadystatechange = function () {
 if (this.responseXML != null) {
 Caption(this.video, this.responseXML);
 } else {
 throw new Error("Can't read resource");
 }
 };
 xhr.video = obj;
 xhr.open("GET", "Br001.xml", true);
 xhr.send("");

But I am getting status=0 and responseXML = NULL.

FollowUp:

After changing the onreadystatechange as below i am getting readyState=1 and status=0 and responsexml=NULL and getting only one callback

xhr.onreadystatechange = function () {
 if (this.readyState == 4
 && this.status == 200) {
 if (this.responseXML != null) {
 Caption(this.video, this.responseXML);
 } else {
 throw new Error("Can't read resource");
 }
 }
};
asked Dec 21, 2013 at 14:54

1 Answer 1

3

readyState goes through multiple stages before the response is available. You have to wait for readyState to change to 4:

xhr.onreadystatechange = function () {
 if (this.readyState === 4) {
 if (this.responseXML != null) {
 Caption(this.video, this.responseXML);
 } else {
 throw new Error("Can't read resource");
 }
 }
};

It's also best to check status (e.g., to make sure it's 200 <= status < 300 (as 2xx are the "ok" responses), although your this.responseXML != null is probably good enough for this use.

answered Dec 21, 2013 at 14:56
Sign up to request clarification or add additional context in comments.

4 Comments

@BrunoLM: Thanks. Feel free to just jump in on those.
@T.JCrowder Please check the question, i have edited.
@akshay: If you're doing this loading the file from your local drive (e.g., file://... rather than http://... or https://...), most browsers disallow ajax calls from file://... resources.
I found the problem. Its with the path name. now getting readyState=4

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.