在一个动作yii2中保存模型和ajax

时间:2015-11-16 05:41:16

标签: php ajax model yii2

我的问题,我不知道在使用Ajax帖子时如何设置$model->code_reg。我想保存我的模型code_reg来循环我的ajax帖子。但它的我的控制器创建不起作用,除了它

这是我的表格:

<div class="form-group">
    <?= $form->field($model, 'code_reg')->textInput(['readonly' => true]) ?> 
</div> <!--I'm using random code and It's was display for this--> 
<table id="sampleTbl", class="table table-striped table-bordered">
    <thead>
        <th>Name</th>
        <th>Age</th> 
    </thead><tbody>
        <tr>
            <td>William</td>
            <td>29</td>
        </tr><tr>
            <td>Nency</td>
            <td>25</td>
        </tr>
    </tbody>
</table>

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

这是我的jQuery函数:

$('#idOfButton').click(function(){
    var TableData = new Array();
    $('#sampleTbl tr').each(function(row, tr){
        TableData[row]={
            'name' : $(tr).find('td:eq(0)').text(),
            'age' : $(tr).find('td:eq(1)').text()
        }
    }); 
    TableData.shift();  // first row will be empty - so remove
    var jsonEncode = JSON.stringify(TableData);
    // alert(jsonEncode);

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

这是我的控制器actionCreate()

$model = new Mutiplearray();

if(Yii::$app->request->isAjax) {
    $tableData = stripcslashes($_POST['pTableData']);
    $tableData = json_decode($tableData, true);
    foreach ($tableData as $key) {
        $model->isNewRecord = true;
        $model->id = NULL;
        $model->name = $key['name'];
        $model->age = $key['age'];
        $model->code_reg = $model->code_reg; // <---This is my problem I can't save it `code_reg` for ajax looping 
        $model->save();
    }

    return $this->redirect(['index']);
} else {
    return $this->render('create', [
        'model' => $model,
    ]);
} 

当我这样使用not set时,我得到了code_reg。当我使用ajax时如何保存模型?

0 个答案:

没有答案