jQuery的AJAX返回的数据:JSON和HTML混? [英] jQuery ajax returned data: json and html mix?
本文介绍了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
}
}
});
这篇关于jQuery的AJAX返回的数据:JSON和HTML混?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文