【问题标题】:How to post Json in form to controller then save to database如何将 Json 以表单形式发布到控制器然后保存到数据库
【发布时间】:2015-10-22 11:04:26
【问题描述】:

我有一个带有示例表值的表单,我的表 (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 控制器:

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

【问题讨论】:

  • 您在提交时收到什么响应标头?
  • 当我显示警告它变得像这样 `[[william,23],[lia,22],[roy,18]] 。然后想保存到数据库
  • 是的,但是响应头是什么?打开 DevTools 并提交。然后带着响应头回到这里。它在网络下。
  • 你必须在 exit() 之前调用 $model->save() 方法。还要在验证后检查模型中的错误
  • 好的,我认为您的 javascript 正在运行,但您的控制器未正确处理,现在我将发布答案

标签: javascript php json controller yii2


【解决方案1】:

使用 lopping foreach 保存数组:

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

【讨论】:

    【解决方案2】:
    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,
            ]);
        } 
    }
    

    你可以看看这个,如果有问题我们会纠正他们

    【讨论】:

    • 有错误$decode = json_decode((string) $json, $asArray)case JSON_ERROR_SYNTAX: throw new InvalidParamException('Syntax error.');
    • 你能检查你的视图文件编码吗?编码应该是utf-8
    • 很抱歉再次打扰您,我已经尝试过此代码。然后我稍微改变一下这段代码,它就可以工作了。但我有新问题你能帮我吗?我只是更新我的代码和我的新问题@NuriddinRashidov
    猜你喜欢
    • 2017-05-31
    • 1970-01-01
    • 2016-07-12
    • 2015-08-02
    • 1970-01-01
    • 2017-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多