将以下函数添加到js中:
save_as = document.getElementById("saveas");
// this functions submits the html structure needed to be saved, via an ajax request
function generateHtmlFile(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) { // XMLHttpRequest.DONE == 4
if (xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
else if (xmlhttp.status == 400) {
alert('There was an error 400');
}
else {
alert('something else other than 200 was returned');
}
}
};
xmlhttp.open("POST", "generate_html_file.php", true);
// the style, in case it's needed in the output html page
var style = '<style>table,tr,td{border:1px solid black;text-align:center;}</style>';
// get all table rows, except the one that contains the buttons
var my_table_children = document.querySelectorAll('#my_table tr:not(.buttons)');
var my_table_html = '<table>';
// loop over table rows to filter them from white spaces & line breaks.
for(var i = 0; i < my_table_children.length; i++){
my_table_html += my_table_children[i].outerHTML.replace(/>\s+</g, "><")
}
my_table_html += '</table>';
var data = new FormData();
data.append('html',style + my_table_html);
xmlhttp.send(data);
}
save_as.addEventListener("click",generateHtmlFile);
将id添加到表元素:
<table id="my_table">
将类添加到按钮容器行“”:
<tr class="buttons">
<table id="my_table">
<tr>
<td></td>
<td>mon</td>
<td>tue</td>
<td>web</td>
<td>thu</td>
<td>fri</td>
</tr>
<tr>
<td>1</td>
<td><input type="text"></td>
<td><input type="text"></td>
<td><input type="text"></td>
<td><input type="text"></td>
<td><input type="text"></td>
</tr>
<tr>
<td>2</td>
<td><input type="text"></td>
<td><input type="text"></td>
<td><input type="text"></td>
<td><input type="text"></td>
<td><input type="text"></td>
</tr>
<tr>
<td>3</td>
<td><input type="text"></td>
<td><input type="text"></td>
<td><input type="text"></td>
<td><input type="text"></td>
<td><input type="text"></td>
</tr>
<tr>
<td>4</td>
<td><input type="text"></td>
<td><input type="text"></td>
<td><input type="text"></td>
<td><input type="text"></td>
<td><input type="text"></td>
</tr>
<tr class="buttons">
<td colspan="3">
<input type="button" value="submit" id="submit">
</td>
<td colspan="3">
<input type="button" value="saveas" id="saveas">
</td>
</tr>
</table>
然后,下面是生成html文件的php脚本:
<?php
if(!empty($_POST['html']))
{
$html_file = fopen("html_output.html", "w") or die("Unable to open file!");
fwrite($html_file, $_POST['html']);
fclose($html_file);
echo "saved successfully";
}
else{
echo "false";
}