【发布时间】:2014-01-11 15:49:30
【问题描述】:
我有这个 ajax 请求从我的服务器获取数据,默认情况下dataType 始终是html。但是有时候它会从服务器返回json,所以我想检查返回的数据是不是html然后执行A else执行B。可以吗?
我的 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时出现此错误,
SyntaxError: JSON.parse: 意外字符
那么我怎样才能让这段代码通用?
【问题讨论】:
-
确保您将数组解析为 json_encode() ?
-
对于 json 数据是。但如果返回的数据是html,我不使用
json_encode。 -
你可以试试这个:
dataType: "json" || "html",,你可以尝试使用typeof()方法返回数据,如果是object,则将其处理为json。
标签: javascript ajax json jquery