解决Ajax动态生成表格时出现undefined的问题

作者:窗边听雨时间:2026-10-26 21:52:09浏览:378

本文分析在使用jQuery Ajax动态拼接HTML表格时,因未初始化字符串变量导致结果头部出现'undefined'的现象。通过展示错误代码与修正后的初始化赋值操作,提供具体的修复方案,确保动态生成的表格内容准确显示。

Ajax动态表格生成出现undefined的原因分析

页面包含两个表格,在调用Ajax请求后,程序会隐藏其中一个表格,并通过HTML字符串拼接生成另一个表格。然而,新生成的表格顶部出现了一个“undefined”字样。需要分析该问题的成因并提供解决方案。具体代码实现如下所示:


问题代码示例

相关代码片段如下:

 
<script type="text/javascript">
$(function(){
if($.browser.msie)
{ 
$("#country").get(0).attachEvent("onpropertychange",function (o){
var countr = o.srcElement.value;
$("#tabb1").hide();
$.ajax({
type: "post",
url: "/yoblhtjfx/queryCountryAjax.action",
data: "country="+countr+"&jsoncallback=?",
dataType: "json",
success: function(json)
{ 
var tableHTML;
tableHTML+="<table id='tabb1' border='1' width='100%'>";
tableHTML+="<tr>";
tableHTML+="<td style='text-align: center' >选择</td>";
tableHTML+="<td style='text-align: center' >区域码</td>";
tableHTML+="<td style='text-align: center' >国别名称</td>";
</tr>";
var list = json.list;
for(var i=0;i<list.length;i++)
{ 
tableHTML+="<tr>";
tableHTML+="<td style='text-align: center'><input type='radio' name='radioo' value='"+list[i][1]+"' /></td>";
tableHTML+="<td style='text-align: center'>"+list[i][0]+"</td>";
tableHTML+="<td style='text-align: center'>"+list[i][1]+"</td>";
</tr>";
} 
</table>";
$("#querycountrydiv").html(tableHTML);
} 
}); 
}); 
} 
}); 
function returnVal()
{ 
var valu;
for(var i = 0;i < document.getElementsByName("radioo").length;i++)
{ 
if(document.getElementsByName("radioo")[i].checked == true)
{ 
valu = document.getElementsByName("radioo")[i].value;
} 
} 
window.opener.document.getElementById("foreignUnitCountry").value = valu;
window.close();
} 
</script>
</head>
<body>
<div align="center" style="width:100%;">

输入名称搜索:


页面HTML结构

相关代码片段如下:

 
<input id="country" name="country" value="">
</div>
<hr id="hr" />
<div id="querycountrydiv" name="querycountrydiv" style="width:100%; height:80%; overflow:auto; border:1px solid #000000;">
<table id="tabb1" border="1" width="100%">
<tr>
<td style="text-align: center" nowrap="nowrap">选择</td>
<td style="text-align: center" nowrap="nowrap">区域码</td>
<td style="text-align: center" nowrap="nowrap">国别名称</td>
</tr>
<c:forEach items="${list}" var="list">
<tr>
<td style="text-align: center" nowrap="nowrap"><input type="radio" name="radioo" value="${list[1] }" /></td>
<td style="text-align: center" nowrap="nowrap">${list[0] }</td>
<td style="text-align: center" nowrap="nowrap">${list[1] }</td>
</tr>
</c:forEach>
</table>
</div><br>
<hr id="hr" />
<div>
<input id="button" type="button" value="确定" onclick="returnVal();" />
<input id="button" type="button" value="关闭" onclick="window.close();" />
</div>
</body>
</html>

修正后的代码方案

上述代码中存在一处语法或逻辑瑕疵,修正后的关键代码段如下所示:


success: function(json) {


var tableHTML = "";


…
作者最新文章