[英]How to POST js Table cell values to PHP and INSERT to MYSQL database
我有一個動態 HTML 表,我只是使用 JavaScript 調用 id,遍歷數據並捕獲單元格值。
問題- 我如何將此數據發布到測試 save.php 頁面以將整個表插入我的 MySQl 數據庫?
var table = document.getElementById('table'),
rows = table.getElementsByTagName('tr'),
i, j, cells, OS_d,roleApp_d,Men_d,vcpu_d,Val_d,Per_d,hw_d ;
for (i = 1, j = rows.length; i < j; ++i) {
cells = rows[i].getElementsByTagName('td');
if (!cells.length) {
continue;
}
OS_d = cells[1].firstChild.value;
roleApp_d = cells[2].firstChild.value;
vcpu_d = cells[3].firstChild.value;
Men_d = cells[4].firstChild.value;
Val_d = cells[5].firstChild.value;
Per_d = cells[6].firstChild.value;
hw_d = cells[7].firstChild.value;
}
--- 需要幫助的部分
$.ajax({
type: "POST",
url: 'Save.php',
data: ({data:OS_d, roleApp_d, vcpu_d, Men_d, Val_d, Per_d, hw_d}),
success: function(data) {
alert(data);
}
});
PHP 端保存.php
<?php
$test = $_POST['data'];
echo $test;
?>
Just quick code, not tested it so your post data should be like this:
var table = document.getElementById('table'),
rows = table.getElementsByTagName('tr'),
i, j, cells, OS_d,roleApp_d,Men_d,vcpu_d,Val_d,Per_d,hw_d ;
var p_row = '[';
for (i = 1, j = rows.length; i < j; ++i) {
cells = rows[i].getElementsByTagName('td');
if (!cells.length) {
continue;
}
p_row += "{";
p_row +='"OS_d":"'+cells[1].firstChild.value+'",';
p_row +='"roleApp_d":"'+ cells[2].firstChild.value+'",';
p_row +='"vcpu_d":"'+ cells[3].firstChild.value+'",';
p_row +='"Men_d":"'+ cells[4].firstChild.value+'",';
p_row +='"Val_d":"'+ cells[5].firstChild.value+'",';
p_row +='"Per_d":"'+ cells[6].firstChild.value+'",';
p_row +='"hw_d":"'+ cells[7].firstChild.value+'"';
p_row += '},';
}
p_row = (p_row).replace(new RegExp("[,]+$"), "");
p_row += ']';
var formData = new FormData();
formData.append('data',p_row);
fetch("/save.php", {
method: "POST",
body: formData
}).then(function (response) {
console.log(response);
}).catch(function (error) {
console.error(error, "code: " + error.status);
});
我想通了,所以我決定與社區分享。 感謝您的支持。
$.ajax({
type: "POST",
url: 'test.php',
data: {p_row : p_row },
success: function(data){
alert(data);
}
});
}
On the test.php side
<?php
$data = false;
if(isset($_POST['p_row'])){
$data = $_POST['p_row'];
}
echo 'Received Data: ' . $data ;
//$conn->close();
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.