说明:
Ajax提交html页面表单,生成表格。
运行效果:
示例源码:
HTML页面:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>表格生成器</title> <link rel="stylesheet" href="http://demo.h-ui.net/H-ui.admin/3.1/static/h-ui/css/H-ui.min.css"> </head> <body> <div class="panel panel-default" style="width:600px;margin:0 auto"> <div class="panel-header selected">Ajax+PHP生成表格</div> <div class="panel-body" style="display: block;"> <form action="" method="" class="form form-horizontal responsive" name="demoform" id="demoform"> <div class="row cl"> <label class="form-label col-xs-3">请输入行数:</label> <div class="formControls col-xs-8"> <input type="text" class="input-text" placeholder="输入数字" name="rowNumber" id="rowNumber"> </div> <label class="form-label col-xs-3">请输入列数:</label> <div class="formControls col-xs-8"> <input type="text" class="input-text" placeholder="输入数字" name="columnNumber" id="columnNumber"> </div> </div> <div class="row cl"> <div class="col-xs-8 col-xs-offset-3"> <button type="button" class="btn btn-primary radius" id="btnGenerate">生成</button> </div> </div> </form> </div> </div> <hr> <div id="result" style="margin: 0 auto; text-align: center;width:600px"></div> <script> var btnValidateValidate = document.getElementById('btnGenerate'); btnValidateValidate.onclick = function () { // console.log(typeof btnValidateValidate); // console.log(phoneNumber.value) var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { if(xhr.readyState == 4 && xhr.status == 200) { var result = xhr.responseText; var h2 =document.getElementById('result'); h2.innerHTML = result; } } var rowNumber = document.getElementById('rowNumber'); var columnNumber = document.getElementById('columnNumber'); var data = '?rowNumber='+rowNumber.value + '&columnNumber='+columnNumber.value; xhr.open('get','generateTable.php'+data, true); xhr.send(null); } </script> </body> </html>
PHP页面(generateTable.php)
<?php $rowNumber = isset($_GET['rowNumber']) ? $_GET['rowNumber'] : null; $columnNumber = isset($_GET['columnNumber']) ? $_GET['columnNumber'] : null; if ($rowNumber !== null && $columnNumber !== null) { $result = ''; $result .= '<table border="1" cellspacing="0" cellpadding="5" width="100%">'; $result .= "<caption>$rowNumber". "×" ."$columnNumber 表格</caption>"; for($i= 1;$i <=$rowNumber; $i++)//生成行 { $result .= '<tr>';//行开始 for($j=1; $j<=$columnNumber; $j++)//生成列 { $result .= '<td>'; $result .=' '; $result .= '</td>'; } $result .= '</tr>';//行结束 } $result .= '</table>'; echo $result; }