gpt4 book ai didi

javascript - 如何将表单中的 Json 发布到 Controller 然后保存到数据库

转载 作者:可可西里 更新时间:2023-10-31 23:03:14 26 4
gpt4 key购买 nike

我有一个带有示例表值的表单,我的表 (id=sampleTbl) hv 2 列名称和年龄。当我点击 submitButton (id=idOfButton) 时,我想将它保存到我的数据库表 person(id=AI,name,age)

在我的代码下方,这是我的 Javascript 代码:

<?php  
$script = <<< JS

$('#idOfButton').click(function(){
var myTableArray = [];
$("table#sampleTbl tr").each(function () {
var arrayOfThisRow = [];
var tableData = $(this).find('td');
if (tableData.length > 0) {
tableData.each(function () {
arrayOfThisRow.push($(this).text());
});
myTableArray.push(arrayOfThisRow);
}
});
var jsonEncode = JSON.stringify(myTableArray);
// alert(jsonEncode);

$.ajax({
type: "POST",
data: "pTableData=" + jsonEncode,
success: function(msg){
// alert(msg);
},
});

});

JS;
$this->registerJs($script);
?>

这是我的 actionCreate Controller :

public function actionCreate()
{
$model = new Person();

if(isset($_POST['pTableData'])) {
$tableData = stripcslashes($_POST['pTableData']);
$tableData = json_decode($tableData, true);
$model->name = $tableData[0]['name'];
$model->age = $tableData[0]['age'];
$model->save();
return $this->redirect(['index']);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}

我的表格:

<?php $form = ActiveForm::begin(); ?>

<table id="sampleTbl", class="table table-striped table-bordered">
<thead>
<tr id="myRow">
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr>
<td>william</td>
<td>32</td>
</tr>
<tr>
<td>Muli</td>
<td>25</td>
</tr>
<tr>
<td>Sukoco</td>
<td>29</td>
</tr>
</tbody>
</table>

<div class="form-group">
<?= Html::submitButton('Create',['class' => 'btn btn-success', 'id' => 'idOfButton']) ?>
</div>

<?php ActiveForm::end(); ?>

我不知道如何保存所有值数组。当我像 $tableData[0]['name']; 那样使用时,它只保存第一行。如何保存所有值(value)??

最佳答案

使用循环 foreach 来保存一个数组:

foreach ($tableData as $key) {
$model->isNewRecord = true;
$model->id = NULL;
$model->name = $key['name'];
$model->age = $key['age'];
$model->save();
}

关于javascript - 如何将表单中的 Json 发布到 Controller 然后保存到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33279502/

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