Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
588 views
in Technique[技术] by (71.8m points)

jquery - Javascript: How to tell whether AJAX response is JSON

I've got an AJAX request that expects JSON in response.

But there's a possibility that what gets returns may not be JSON, but rather an HTML error page (unfortunately, with response type 200).

How can I tell whether the response is JSON or not?

(I'm using jQuery, if that helps. But I can't use any plugins.)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Well, if you are using jQuery and you specify the dataType property of the $.ajax() call to json then jQuery will try to parse the JSON, and if it isn't JSON should call the error() callback.

$.ajax({
    url: '/my/script.ext',
    dataType: 'json',
    success: function(data, textStatus, jqXHR) { /*YAYE!!*/ },
    error: function(jqXHR, textStatus, errorThrown) { /*AWWW... JSON parse error*/ }
});

EDIT

For anyone not using jQuery that lands here, the basic idea is to try and parse it as json and catch the error:

var data = 'some_data';

try {
    data = JSON.parse(data);
} catch(e) {
    //JSON parse error, this is not json (or JSON isn't in your browser)
}

//act here on the the parsed object in `data` (so it was json).

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...