views:

222

answers:

2

What is the best method to detect xml in JavaScript

e.g. is it possible to detect the mime type of a document - particularly if it is text/xml in JavaScript.

this needs to work in Chrome.

thanks,

Josh

A: 

You can't determine what the mime-type is with Javascript. I would recommend doing checks on the data returned to see if it is valid XML before you try to parse it. (I'm only assuming what you're trying to do. I can provide a more rigid example if you clarify what your goal is.)

Ian Elliott
+1  A: 

If you are using XMLHttpRequest to get this data, then you can simply check for the Content-Type header using the getResponseHeader method (granted that the server sends the appropriate headers).

var getFile = function(address, responseHandler) {
  var req = new XMLHttpRequest();  

  req.open('get', address, true);  
  req.onreadystatechange = responseHandler;
  req.send(null);  
}

var responseHandler = function(resp) {
  if ( this.readyState < 4 ) { return; }
  console.log(this.getResponseHeader("Content-Type"));
};

getFile("http://zebrakick.com/some/file", responseHandler);

(I seem to be using this code sample a lot...)

Justin Johnson