[英]Check if Ajax json response data
我在jsp页面中使用jqueryAjax函数来显示html表。 该函数将响应作为json对象返回。 我正在使用json对象,对其进行迭代并显示列值。 但是,如果字段值为空,则html表中的对应值将指定为“未定义”。以下是我的示例代码
$.each(data1, function (i, item) {
trHTML += '<tr><td >' + item.appnName + '</td><td>' + item.Defectsin2014 + '</td><td>' + item.Defectsin2015 + '</td><td>'+
item.DefectsasperBenchmarks +'</td><td>'+item.costDefect + '</td><td>'+ item.req2014 + '</td><td>'+ item.req2015 +'</td><td>' +
item.ba+ '</td><td>'+ item.config+'</td><td>'+ item.Financials+ '</td><td>' + item.bReports + '</td><td>'+
item.qa + '</td></tr>';
});
$('#records_table').append(trHTML);
在上面的例子中,如果某个特定字段在json中不可用,例如,如果item.req2015数据对于特定行不可用,则html表将相应字段显示为``未定义''。我希望应用程序显示一个如果数据不可用,则为空或空白字段。 有什么办法可以达到相同的效果。
任何帮助对此表示感谢。
在使用属性之前,请检查属性并为它们提供默认值。
$.each(data1, function (i, item) {
item.appnName = item.appnName || " ";
item.Defectsin2014 = item.Defectsin2014 || " ";
item.Defectsin2015 = item.Defectsin2015 || " ";
item.costDefect = item.costDefect || " ";
item.req2014 = item.req2014 || " ";
item.req2015 = item.req2015 || " ";
item.ba = item.ba || " ";
item.config = item.config || " ";
item.Financials = item.Financials || " ";
item.bReports = item.bReports || " ";
item.qa = item.qa || " ";
trHTML += '<tr><td >' + item.appnName + '</td><td>' + item.Defectsin2014 + '</td><td>' + item.Defectsin2015 + '</td><td>'+
item.DefectsasperBenchmarks +'</td><td>'+item.costDefect + '</td><td>'+ item.req2014 + '</td><td>'+ item.req2015 +'</td><td>' +
item.ba+ '</td><td>'+ item.config+'</td><td>'+ item.Financials+ '</td><td>' + item.bReports + '</td><td>'+
item.qa + '</td></tr>';
});
$('#records_table').append(trHTML);
甚至可以通过内联决策缩短:
trHTML += '<tr><td >' + (item.appnName || " ") + '</td><td>' + (item.Defectsin2014 || " ") + '</td><td>' + (item.Defectsin2015 || " ") + '</td><td>'+
(item.DefectsasperBenchmarks || " ") +'</td><td>'+(item.costDefect || " ") + '</td><td>'+ (item.req2014 || " ") + '</td><td>'+ (item.req2015 || " ") +'</td><td>' +
(item.ba || " ") + '</td><td>'+ (item.config || " ")+'</td><td>'+ (item.Financials || " ") + '</td><td>' + (item.bReports || " ") + '</td><td>'+
(item.qa || " ") + '</td></tr>';
通过以下方式设置默认值:
<td>'+ (item.req2015||' ') + '</td>
通过提交的可设置默认值,可以轻松地重新组织:
var fdef = [ 'appnName '," "
,'Defectsin2014', " "
,'Defectsin2015'," "
,'costDefect ', " "
,'req2014 '," "
,'req2015 ', " "
,'ba '," "
,'config ', " "
,'Financials '," "
,'qa ', " "
];
function buildLine(item) {
var out = [];
for (var i= 0,l=fdef.length;i<l;++i) {
out.push(item[fdef[i][0]] || fdef[i][1]);
}
return '<tr><td>' + out.join('</td><td>') + '</td></tr>'
}
你可以用这个
if(item.hasOwnProperty('req2015')){
//add it
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.