1

I have a simple PHP script which returns a simple JSON response:

$data=array('a'=>'apple');
header('Content-Type: application/json');
print json_encode(array($date));

Using JavaScript, I try to read the data:

var url='…';
var xhr=new XMLHttpRequest();
xhr.open('get', url, true);
xhr.send(null);
xhr.onreadystatechange=function() {
    if(this.readyState==4) {
        alert(this.responseText);
        alert(this.responseType);
    }
};

The code works for the most part, but I cannot get anything for the responseType property. I was expecting it to be json but anything would be helpful.

I thought that a suitable mime type would do the job. I have tried it in Firefox, which has generally very good support, as well as in Safari.

What am I missing?

Manngo
  • 14,066
  • 10
  • 88
  • 110
  • Found this (http://stackoverflow.com/questions/9845401/xmlhttprequest-responsetype-json-giving-error-syntax-err-dom-exception-12). Looks like the responseType JSON isn't supported by all browsers – sanderbee Sep 09 '15 at 07:55

2 Answers2

1

responseType is not the MIMEType of the server's response. You can set it before sending the XMLHttpRequest in order to influence the type of the response attribute when the response arrives. For details see XMLHttpRequest Level 1 at W3C.org.

You access the MIMEType of the server's response as this.getResponseHeader("Content-Type").

mkiever
  • 894
  • 5
  • 13
0

The Content-type header is just used as info for your application. The browser doesn't care what it is. The browser just returns you the data from the AJAX call. If you want to parse it as JSON, you need to do that on your own.

The header is there so your app can detect what data was returned and how it should handle it. You need to look at the header, and if it's application/json then parse it as JSON.

This is actually how jQuery works. If you don't tell it what to do with the result, it uses the Content-type to detect what to do with it.

Found at HTTP Content-Type Header and JSON

Community
  • 1
  • 1
Fky
  • 2,133
  • 1
  • 15
  • 23