jQuery的AJAX返回的数据:JSON和HTML混?
问题描述:
我有这样的Ajax请求从我的服务器获取数据,而的dataType
总是 HTML
默认。但有时它会从服务器返回JSON,所以我要检查,如果返回的数据是HTML然后执行一个其他执行B.这可能吗?
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, so I want to check if the returned data is html then execute A else execute B. Is it possible?
我的jQuery,
$.ajax({
type: "GET",
dataType: "html",
url: request_url,
context: $('#meat'),
async: true,
beforeSend: function () {},
success: function (returndata, status, jqXHR) {
if ($.parseJSON(returndata) === false) A;
else B.
}
});
在返回的数据是我得到这个错误 HTML
,
I get this error when the returned data is html
,
语法错误:JSON.parse:意外的字符
SyntaxError: JSON.parse: unexpected character
那么,如何可以让这个code 多功能
So how can I make this code versatile?
答
我不知道是否有更好的办法,但你可以使用try ... catch
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
}
}
});