1

我有一个网站,用户可以添加或删除自己喜欢的书籍。我在页面的每一行都添加了“添加”和“删除”按钮。我可以在会话数组中添加喜欢的书籍,这没有问题。但我无法从“用户最喜欢的书单”中删除一行。

我用过jquery,ajax。我可以取消设置行,但我想要的是从会话中完全删除该行并再次订购。尽管我取消了行的设置,但会话的元素数并没有改变。

这是代码:

    //There are rows in $newdata. That is to say, newdata array is not empty now.
    // I just add newdata array here to show that there is an array called newdata.

    var $newdata = array();

    function delete_row($rowid) {

    if (isset($rowid)) {

    $this->newdata = $this->session->userdata('contents');
    unset($this->newdata[$rowid]['id']);
    unset($this->newdata[$rowid]['name']);
    unset($this->newdata[$rowid]['author']);
    unset($this->newdata[$rowid]['year']);

    $this->session->set_userdata(array('contents' => $this->newdata));

    $contents = $this->session->userdata('contents');

    $i = 0;

        foreach ($contents as $key)         
        {
            if ($key['id'] != "") {
                $i++;

            $this->newdata[$i]['id'] = $key['id'];
            $this->newdata[$i]['name'] = $key['name'];
            $this->newdata[$i]['author'] =$key['author'];
            $this->newdata[$i]['year'] =$key['year'];

            } else {

            }
        }

    $this->session->set_userdata(array('contents' => $this->newdata));

    } else {

        echo "There is no row to be deleted";
    }
}

这是查看代码(html):

<div>

        <?php 

        if (count($contents)==0) {
        echo 'There is no favorite book';
        } else {

        echo '<table class="table table-striped">';

        $i = 0;
        echo count($contents);
        foreach ($contents as $items) {

        echo '<tr>';
        echo '<td>'.$items['id'].'</td>';
        echo '<td>'.$items['name'].'</td>';
        echo '<td>'.$items['author'].'</td>';
        echo '<td>'.$items['year'].'</td>';
        echo '<td><button id='.$i .' class="delete_row"><b>DELETE</b></button></td>';
        echo '</tr>';
        $i++;

    }
    echo '</table>';

    }
        ?>
    </div>

这是jQuery代码:

$('.delete_row').click(function(event) {
event.preventDefault();
var id = $(this).attr("id"); 
window.location.href = '/favorite/delete_row/'+id;

 });
4

1 回答 1

1

我认为问题出在 del 按钮 id 上。您正在使用$i变量而不是$items['id']. 因此 JS 重定向会将 count int 而不是项目id发送到删除页面。

改变:

echo '<td><button id='. $i .' class="delete_row"><b>DELETE</b></button></td>';

进入:

echo '<td><button id='. $items['id'] .' class="delete_row"><b>DELETE</b></button></td>';
于 2012-08-04T12:17:48.587 回答