如何让AJAX动态加载的表单正常实现提交和重置功能
问题原因
- 核心原因是
forms.html的HTML结构不符合规范:<tr>标签的合法直接子元素只能是<td>或<th>,直接把<form>作为<tr>的子元素属于非法结构。浏览器解析这种非法结构时会自动调整DOM树位置,把<form>元素移到<table>外部,导致原本在form内部的输入框、提交/重置按钮和form失去关联,自然触发不了提交、重置行为。 - 单独打开
forms.html功能正常是因为浏览器对单页非法结构的容错解析策略和通过innerHTML插入到现有DOM的解析策略不同,单独打开时刚好保留了form和控件的关联,插入现有页面时关联被打断。
解决方案
方案1:修正HTML结构(推荐)
把<form>放到合法的节点位置,比如每个表单单独用一个嵌套表格包裹,保证结构符合HTML规范,示例forms.html代码如下:
<table> <tr> <td> <form name="someform" method="post" action="someaction.php"> <table><tr> <td><input type="text" name="somefield" /></td> <td><button type="submit">提交</button></td> <td><input type="reset" value="重置" /></td> </tr></table> </form> </td> </tr> <tr> <td> <form name="someform" method="post" action="someaction.php"> <table><tr> <td><input type="text" name="somefield" /></td> <td><button type="submit">提交</button></td> <td><input type="reset" value="重置" /></td> </tr></table> </form> </td> </tr> <tr> <td> <form name="someform" method="post" action="someaction.php"> <table><tr> <td><input type="text" name="somefield" /></td> <td><button type="submit">提交</button></td> <td><input type="reset" value="重置" /></td> </tr></table> </form> </td> </tr> </table>
方案2:通过form属性绑定关联
如果不想改动现有布局结构,可以给每个表单加唯一id,所有输入框、按钮通过form属性和对应表单绑定,哪怕DOM结构被浏览器自动调整,关联关系也不会失效,示例forms.html代码如下:
<table> <tr> <form id="form1" name="someform" method="post" action="someaction.php"></form> <td><input type="text" name="somefield" form="form1" /></td> <td><button type="submit" form="form1">提交</button></td> <td><input type="reset" value="重置" form="form1" /></td> </tr> <tr> <form id="form2" name="someform" method="post" action="someaction.php"></form> <td><input type="text" name="somefield" form="form2" /></td> <td><button type="submit" form="form2">提交</button></td> <td><input type="reset" value="重置" form="form2" /></td> </tr> <tr> <form id="form3" name="someform" method="post" action="someaction.php"></form> <td><input type="text" name="somefield" form="form3" /></td> <td><button type="submit" form="form3">提交</button></td> <td><input type="reset" value="重置" form="form3" /></td> </tr> </table>
额外优化建议
test.html中使用的是同步AJAX请求(xhttp.open第三个参数为false),会阻塞页面主线程导致点击按钮后页面卡顿,建议改成异步请求,只需要把第三个参数改为true即可,不影响现有逻辑。
内容的提问来源于stack exchange,提问作者mlazatin
相关产品推荐
相关产品推荐

