【发布时间】:2018-08-23 14:49:50
【问题描述】:
我有一个表单,在提交时会根据用户的输入显示具有不同数据的表格(对 php 文件的 ajax 请求)。每次用户提交表单时,我有没有办法用新信息动态重新加载表格?截至目前,数据在每次提交后一直附加到表中,并继续添加到最后一次提交数据中。任何建议将不胜感激,谢谢!
HTML
<form id = "infoForm"
action="file.php" method="post">
<b>Enter info:</b> <input type = "text" name = "info"
id = "infoInput" maxlength = "10" required >
<button type = "submit" id = "submit_form">Submit</button>
</form>
<table id = "infoTable">
<tbody>
<tr>
<th>Name</th>
<th>Number</th>
</tr>
</tbody>
</table>
JavaScript
$("#infoForm").submit(function() {
$("#infoTable").fadeIn(400);
//InputData is an array that contains the user input data
$.post( "file.php", InputData,
function( data ){
var names = data.names; //from PHP file
var numbers = data.numbers; //from PHP file
var namesArray = names.split(',');
var numbersArray = numbers.split(',');
for(var i = 0; i < namesArray.length; i++) {
$("#infoTable > tbody").append('<tr><td>'+namesArray[i]+'</td><td>'+numbersArray[i]+'</td></tr>');
}
}, "json");
return false;
});
【问题讨论】:
-
在
append()之前添加对.empty()的调用 -
另外,将
names和numbers值作为 JSON 中的数组而不是您需要手动拆分的字符串返回不是更有意义吗? -
@RoryMcCrossan 是的,您将这些值作为数组返回是对的。感谢您的帮助!
-
@ski11s - 看看这个 Stackoverflow 问题和答案,它可能会帮助您改进这个解决方案:stackoverflow.com/questions/18673860/…
-
@Chris 我一定会看看的。谢谢!
标签: javascript jquery html