如何用jQuery判断返回的JSON是简单字符串还是编码对象
如何在jQuery Success回调中区分返回的JSON对象与字符串
嘿,针对你遇到的这个问题,我给你整理了几种靠谱的解决方案,直接就能套用在你的代码里:
方案一:通过类型判断区分
因为后端正常返回的是解析后的JSON对象,异常时返回的是字符串,所以可以直接用typeof做判断,同时注意排除null(因为typeof null会返回'object'):
success: function (response) { // 确认是对象且不是null if (typeof response === 'object' && response !== null) { $('#textareaDescription').val(response.Description); } else { // 这里response就是异常返回的字符串 ModalError(response); } }, error: function (XMLHttpRequest, textStatus, errorThrown) { ModalError(textStatus + " - " + errorThrown); }
方案二:结合业务属性判断(更贴合你的场景)
既然正常返回的对象包含Description属性,你也可以直接检查这个属性是否存在,这样判断更贴合你的业务逻辑:
success: function (response) { // 先确保response不是null/undefined,再检查属性 if (response && typeof response.Description !== 'undefined') { $('#textareaDescription').val(response.Description); } else { // 处理异常情况,兼容非字符串的意外返回 const errorMsg = typeof response === 'string' ? response : '发生未知错误'; ModalError(errorMsg); } }, error: function (XMLHttpRequest, textStatus, errorThrown) { ModalError(textStatus + " - " + errorThrown); }
额外小建议:统一后端返回格式
其实从长远来看,最好让后端统一返回格式,不管成功还是失败都返回标准JSON对象,比如:
- 成功时:
return Json(new { Success = true, Data = vResult }, JsonRequestBehavior.AllowGet) - 异常时:
return Json(new { Success = false, Message = UnhandledError }, JsonRequestBehavior.AllowGet)
这样前端只需要判断response.Success就能区分状态,代码逻辑会更清晰,也能避免类型判断可能带来的潜在问题。
内容的提问来源于stack exchange,提问作者gchq
相关产品推荐
相关产品推荐

