我具有一个jQuery函数,该函数期望字符串作为响应。但是,在非常罕见的情况下,它将得到一个编码的对象。因此我正在使用:
function is_json(str) {
try {
var o = JSON.parse(str);
// Handle non-exception-throwing cases:
// Neither JSON.parse(false) or JSON.parse(1234) throw errors, hence the type-checking,
// but... JSON.parse(null) returns null, and typeof null === "object",
// so we must check for that, too. Thankfully, null is falsey, so this suffices:
if (o && typeof o === "object") {
return o;
}
} catch (e) {
}
return false;
}
检查我们是否正在收到JSON响应。不幸的是,即使我们是,该函数也返回false。使用开发人员面板证实了这一点。
这是脚本:
$('.create-viewer').on('click', function () {
var id = $(this).attr('data-id');
var table = $(this).attr('data-table');
var url = '/neou_cms/ajax/table_render?id=' + id + '&table=' + table;
$.get(url, function (data) {
console.log(data);
if (is_json(data)) {
console.log('data_is_json');
var obj = JSON.parse(data);
data = obj.msg;
// do something with data...
}
bootbox.dialog({
message: data,
title: $_lang.view_header,
buttons: {
success: {
label: $_lang.actions_ok,
className: 'btn-primary'
}
}
});
});
});
我的响应具有用Chrome确认的application/json
标头,并且采用以下格式:
{"status":"error","msg":"Some message here."}
根据JSONLINT验证
如果未向$.get
指定数据类型参数,则它将尝试从Content-type
标头推导类型。在您的情况下,由于它说application/json
,因此jQuery会自动为您解析,而data
将是解析的对象。因此,您可以简单地做:
$.get(url, function(data) {
if (typeof data == 'object') {
data = data.msg;
}
...
});