[英]how to insert all data in table to database using ajax
以下是我的代碼以及我到目前為止所做的事情。
單擊#orderSave按鈕后如何使用ajax將表中的所有數據插入數據庫?
<table class="table table-sm table-striped table-hover" id="tbltrs">
<thead>
<tr>
<th>Name</th>
<th>Price</th>
<th>Qty</th>
</tr>
</thead>
<tbody id="tbodydata"></tbody>
</table>
<button type="button" id="orderSave" class="btn btn-sm btn-secondary">Process</button>
$("#code").bind('blur keypress',function(event){ event.preventDefault(); if (event.keyCode === 13 || event.type == 'blur') { var vals = $('#code').val(); $.ajax({ type: 'POST', url: 'check.php', 緩存: false, dataType:"json", data:{code: vals}, 成功: function(data) { if(data['ok'] > 0){ var qty = 1; var elems = $('#tbltrs td').filter(function(){ return $.trim($(this) .text()) === data['name']; }); if (elems.length) { var qty = parseInt(elems.parent('tr').find('#qty').val() ) + 1; elems.parent('tr').find('#qty').val(qty); } else { var html = ''; html += ''; html += ''+data[' product']+''; html += ''+data['price']+''; html += ''; $('#tbodydata').prepend(html); } } else {alert('none ');} $('#code').val('').focus(); }, error:function(err){alert("error"+JSON.stringify(err)); } }); } });
$('#orderSave').click(function() {
$.ajax({
type: 'POST',
url: 'orders.php',
cache: false,
data:............,
success: function(data) {
printWindow = window.open("", "", "height=1, width=1");
printWindow.document.write(data);
printWindow.focus();
printWindow.print();
printWindow.close();
},
error:function(err){alert("error"+JSON.stringify(err)); }
});
});
您需要序列化表單並使用提交事件我們使用e.preventDefault()
來不提交
您確實需要 NAME 屬性
另外,我建議您在追加/追加數據時不要使用 ID
您忘記了使用 document.write 的 document.close
最后,當您使用模板文字時,html 更具可讀性
$('#tbodydata').prepend(`<tr>
<td class="d-none"><input type="text" name="id" id="id" value="${data['id']}"></td>
<td class="col" name="product">${data(product)}</td>
<td class="col" name="price">${data(price)}</td>
<td class="col"><input type="text" name="qty" id="qty" value="${qty}"></td></tr>`);
$("#yourForm").on("submit",function(e) {
e.preventDefault()
const data = $(this).serialize();
$.ajax({
type: 'POST',
url: 'orders.php',
cache: false,
data: data,
success: function(data) {
printWindow = window.open("", "", "height=1, width=1");
printWindow.document.write(data);
printWindow.document.close();
printWindow.focus();
printWindow.print();
printWindow.close();
},
error: function(err) {
alert("error" + JSON.stringify(err));
}
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.