Search code examples
javascriptjsongoogle-chromexmlhttprequestinternet-explorer-11

JSON response parsed/not parsed for Chrome and IE


XMLhttpRequest returns JSON with

abc.responseType = 'json';

var answer = abc.response;

It works in chrome if I do the following:

if (answer.success) {
        window.alert("GOODBOY!");
      } else {
        window.alert("YOUFAILED" + answer.message);
      }

However, IE would allways skip the if even when successwas true For it to work in Internet Explorer I tried to parse it (again?)

 var answer = abc.response;
 var answer2 = JSON.parse(abc.response);
      if (answer2.success) {
            window.alert("GOODBOY!");
          } else {
            window.alert("YOUFAILED" + answer2.message);
          }

Which worked in IE but obviously leads to the following error in chrome:

Uncaught SyntaxError: Unexpected token o in JSON at position 1

What am I missing? How can I make it work on both browsers?


Solution

  • As IE doesn't support json as a responseType, drop that, use the default text and do

     var answer = JSON.parse(abc.response);