为何我的三元表达式无法识别Ajax返回的NULL值?
解决Ajax返回值判断NULL不生效的问题
看起来你遇到的核心问题是后端返回的NULL并没有被JavaScript识别为原生的null值,导致你的判断条件始终不触发。我来帮你一步步排查和解决:
第一步:先明确实际返回值的类型和内容
首先你需要搞清楚val.HasCustomerArrived到底是什么——是JavaScript的null?undefined?还是字符串类型的"null"?在你的代码前加一行调试代码:
console.log("当前值:", val.HasCustomerArrived, "类型:", typeof val.HasCustomerArrived);
打开浏览器控制台(F12)查看输出,这能帮你精准定位问题根源。
第二步:针对不同情况调整判断逻辑
根据调试结果,对应修改你的三元表达式:
情况1:返回值是字符串"null"
很多后端框架在处理数据库NULL时,会把它序列化为字符串"null"而不是原生JS的null,这时候你的判断条件要改成:
.append($('<td>').attr('id', "tdBookingStatus" + i).html( val.HasCustomerArrived === true ? "Checked in" : val.HasCustomerArrived === "null" ? " " : "Cancelled" ))
情况2:返回值是undefined或原生null
如果调试显示是null或undefined,你可以用更宽松的空值判断来覆盖两种情况(== null会同时匹配null和undefined):
.append($('<td>').attr('id', "tdBookingStatus" + i).html( val.HasCustomerArrived === true ? "Checked in" : (val.HasCustomerArrived == null) ? " " : "Cancelled" ))
情况3:覆盖更多边缘场景
如果返回值还有空字符串""等其他 falsy 值,你可以扩展判断条件:
.append($('<td>').attr('id', "tdBookingStatus" + i).html( val.HasCustomerArrived === true ? "Checked in" : (val.HasCustomerArrived == null || val.HasCustomerArrived === "" || val.HasCustomerArrived === "null") ? " " : "Cancelled" ))
额外建议:优化代码可读性
多层嵌套的三元表达式容易出错,你可以把逻辑抽成变量,让代码更清晰:
let statusText; if (val.HasCustomerArrived === true) { statusText = "Checked in"; } else if (val.HasCustomerArrived == null || val.HasCustomerArrived === "null") { statusText = " "; } else { statusText = "Cancelled"; } .append($('<td>').attr('id', "tdBookingStatus" + i).html(statusText))
这样后续调试和修改也会更方便。
内容的提问来源于stack exchange,提问作者user9677867
相关产品推荐
相关产品推荐

