gpt4 book ai didi

php - 使用 Php、Ajax、JSON 将动态记录保存在数据库中

转载 作者:行者123 更新时间:2023-11-30 00:22:15 24 4
gpt4 key购买 nike

我有一个表,每行包含 1 个数据库记录的字段
动态添加和删除表格行
我想使用ajax将所有文本框数据发送到php文件
表格如下

<table id="tblDmc" frame="box" rules="all" width="100%">
<tr>
<th>Subject</th><th>Total Marks</th><th>Obtained</th><th>Class Highest</th><th>Remarks</th><th>&nbsp;&nbsp;&nbsp;</th>
</tr>
<tr class="subRecord">
<td><input type="text" class="dmcTxt subject"></td>
<td><input type="number" class="dmcTxt total"></td>
<td><input type="number" class="dmcTxt obtained"></td>
<td><input type="number" class="dmcTxt highest"></td>
<td><input type="text" class="dmcTxt remarks"></td>
<td><a href="#" class="removeRow">x<a></td>
</tr>
</table>

Jquery Ajax 代码

$("#btnSave").click(function(){
var data1 = [];
var stdRow = {"s_id":$("#drpClass").val(),"month":$("#drpMonth").val(),"percent":$("#percentage").val(),"grade":$("#grade").val(),"position":$("#position").val(),"curricular":$("#curricular").val()};
data1.push(stdRow);
$("#tblDmc .subRecord").each(function(){
if($(this).find(".subject").val()!="")
{
var rowData = {};
rowData["subject"] =$(this).find(".subject").val();
rowData["total"] =$(this).find(".total").val();
rowData["obtained"] =$(this).find(".obtained").val();
rowData["highest"] =$(this).find(".highest").val();
rowData["remarks"] =$(this).find(".remarks").val();
data1.push(rowData);
}
});
//$(this).after(JSON.stringify(data1));
$.ajax({
url:'savedmc.php',
type:'POST',
data: JSON.stringify(data1),
contentType: "application/json; charset=UTF-8",
success: function(e){
alert(e);
}
});

});

JSON.stringify(data1) 返回以下内容

[
{"std_id":"6","month":"4","percent":"77","grade":"1","position":"33","curricular":"abc"},
{"subject":"Maths","total":"100","obtained":"99","highest":"100","remarks":"remarks"},
{"subject":"Physics","total":"100","obtained":"94","highest":"99","remarks":"emarks"}
]

savedmc.php 中的代码是

<?php print_r($_POST); ?>

返回 NULL array()

我的问题是如何通过ajax将上述json对象/数组发送到php文件,
或者任何替代方案?

最佳答案

用此版本替换 JS 代码中的 ajax 调用:

$.ajax({
url:'savedmc.php',
type:'POST',
dataType: "json",
data: JSON.stringify(data1),
contentType: "application/json; charset=UTF-8",
success: function(e){
alert(e);
}
});

关于php - 使用 Php、Ajax、JSON 将动态记录保存在数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23143046/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com