0

我在视图上使用 ajaxlink 来添加我的提交表单的新行。我需要一个索引来指示创建了哪一行。所以我使用类变量来保存索引。但我发现变量只更改了一次。

这是我的代码

public function actionNewrow()
{
    $this->i++;

    $form = new CActiveForm();
    $temp = new exportprice();

    array_push($this->exps, $temp);
    //echo count($this->exps);

    $i = count($this->exps)-1;

    $html = '<tr><td>'.
                $this->i.$form->labelEx($this->exps[0],'['.$i.']productname').$form->textField($this->exps[0],'['.$i.']productname').$form->error($this->exps[0],'['.$i.']productname')
            .'</td>'.
            '<td>'.
                $form->labelEx($this->exps[0],'['.$i.']trend').$form->textField($this->exps[0],'['.$i.']trend').$form->error($this->exps[0],'['.$i.']trend')
            .'</td>'.
            '<td>'.
                $form->labelEx($this->exps[0],'['.$i.']margin').$form->textField($this->exps[0],'['.$i.']margin').$form->error($this->exps[0],'['.$i.']margin')
            .'</td></tr>';
    echo $html;
}

echo CHtml::ajaxLink("新增",
    Yii::app()->createUrl( 'InputReport/newrow' ),

    // ajax options
    array(
        'error' => 'function(data)   { alert("error!");  }',
        'success' => 'function(data) { $("#exptbl").append(data); }',
        'cache'=>false,
    ),

    // htmloptions
    array(
        'id' => 'handleClick',
    )
);
4

1 回答 1

0

所以你是actionNewrow通过 AJAX 调用一个预定义的类变量$i,你每次都加入它?这就是为什么。PHP 与客户端不一致,因此$i当以这种方式使用时,它将始终等于先前的值,因为++它只会使其 inc 一次。

$i您将需要在客户端通过某种方式将其从解密中发送下来:

  • 从您拥有的行数+1(这对索引重复开放)
  • Housing a $i var in JS and using that within a self defined function (probably outside of the ajaxLink builder) to propogate a new row using the $i var in JS as the class var.

A quick example for you:

var i = <?php echo $this->i // presuming i is a controller car you pass to the view ?>;

$('.add_new_row').on('click', function(){
    $.get('InputReport/newrow', {i:i}, function(data){
        //append your row now
        i++; // inc i here
    });
});

And then in your controller you would do something like:

public function actionNewrow($i = null)
{
    $i = $i===null ? $this->i++ : $i;

    $form = new CActiveForm();
    $temp = new exportprice();

    array_push($this->exps, $temp);
    //echo count($this->exps);

    $i = count($this->exps)-1;

    $html = '<tr><td>'.
                $this->i.$form->labelEx($this->exps[0],'['.$i.']productname').$form->textField($this->exps[0],'['.$i.']productname').$form->error($this->exps[0],'['.$i.']productname')
            .'</td>'.
            '<td>'.
                $form->labelEx($this->exps[0],'['.$i.']trend').$form->textField($this->exps[0],'['.$i.']trend').$form->error($this->exps[0],'['.$i.']trend')
            .'</td>'.
            '<td>'.
                $form->labelEx($this->exps[0],'['.$i.']margin').$form->textField($this->exps[0],'['.$i.']margin').$form->error($this->exps[0],'['.$i.']margin')
            .'</td></tr>';
    echo $html;
}

This should help you out a little hopefully,

于 2012-09-14T08:21:56.837 回答