I have this ajax request to get the data from my server, and the dataType
is always html
by default. But sometimes it would return json from the server
Essentially, your code is just plain wrong - your serverside API is violating all principles of predictability if the return type can vary in an inconsistent manner. Your code should never have to guess at the type of the returned data.
Having said that, a simple try/catch will help as a workaround for the erratic behaviour if you don't want to fix it. Ie.
try {
if ($.parseJSON(returndata) === false) A;
} catch(e) {
// Treat as HTML here.
}
It's not pretty, but that's what you get for having an unpredictable API that isn't pretty to begin with.
I'm not sure if there is a better way, but you could try... catch
$.ajax({
type: "GET",
url: request_url,
context: $('#meat'),
async: true,
beforeSend: function() {
},
success: function (returndata, status, jqXHR) {
var parsed;
try
{
parsed = $.parseJSON(returndata);
// Execute B
}
catch(e)
{
// treat as html then
// do parsing here
parsed = returnData;
// Execute A
}
}
});
may be you need to handle it like this
try{
var response=jQuery.parseJSON('response from server');
if(typeof response =='object')
{
//control would reach this point if the data is returned as json
}
else
{
//control would reach this point if data is plain text
if(response ===false)
{
//the response was a string "false", parseJSON will convert it to boolean false
}
else
{
//the response was something else
}
}
}
catch(exp){
//controls reaches here, if the data is html
}
Since you need to check the html data as well, you may need to take care of this,
Might also need to use a try / catch for exceptions if it is possible that parseJSON is going to be dealing with something other than JSON values (i.e. HTML)
REF:How can I check if a value is a json object?
EDIT:Edited to make code more precise towards solution