如何将表单中的 Json 发布到控制器,然后保存到数据库


How to post Json in form to controller then save to database

我有一个带有示例表值的表单,我的表(id=sampleTbl(hv 2列名称和年龄。 我想将其保存到我的数据库表中 person(id=AI,姓名,年龄(当我单击提交按钮(id=idOfButton(时

在我的 from 代码下面,这是我的 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);
?>

这是我用于操作创建的控制器:

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'];一样使用时,它只保存第一行。 如何保存所有值??

使用 lopping foreach 来保存数组:

foreach ($tableData as $key) {
    $model->isNewRecord = true;
    $model->id = NULL;
    $model->name = $key['name'];
    $model->age = $key['age'];
    $model->save();
}
public function actionCreate()
{
    $model = new Person();
    if (Yii::$app->request->isPost) {            
        $post = file_get_contents("php://input");
        $data = JSON::decode($post, true);
        $model->attributes = $data;//Also check this array, this should be right assoc array, and indexes must be contain model attributes names also
        $response = array();
if($model->save()){
 header('Content-type:application/json');
        $response['success'] = "Everything is good";
   return   $this->render('create', [
            'model' => $model,
            'message' => $model,
        ]);      
}else{
      $response['error'] = "Data not valid";
   return   $this->render('create', [
            'model' => $model,
            'message' => $model,
        ]);
}
    } else {
        return $this->render('create', [
            'model' => $model,
        ]);
    } 
}

你能检查一下吗,如果有什么问题,我们会纠正他们

相关文章: