Search code examples
javascriptjqueryjsoncontent-typegetjson

Should jQuery $.getJSON() method fail when the response is text/html?


Is it possible to force $.getJSON() function to raise an error when we try to get HTML with it (not application/json). It seems that this deferred just returns empty object to then (or done).

How can we find in then handler which content-type was processed in response? I have the situation when server can return HTML instead of JSON when the service isn't available.


Solution

  • $.getJSON() fails when the response is text/html. See this example:

    $.getJSON('http://httpbin.org/html')
      .then(() => console.log('success'), () => console.log('error'))
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>