2018-03-28 17:16:36 2139次浏览 1条回答 0 悬赏 100 金钱

我这边有一个发票打印的需求, 为了做到发票页面代码重用 。 我把发票样式封装了一个widget, 这个widget在页面的是隐藏起来, 打印的时候就打印这个widget里面的内容。初始化的时候传入一个model, 这个widget根据这个model来生成发票内容。正常销售页面已经实现了这个功能。

但是我在销售历史页面做发票补打功能, 这个页面就是一个index页面, 有一个补打的操作,我的想法是在补打的时候,点击某一行记录补打, 就通过一个ajax请求, 去后台请求这条记录的model,然后局部刷新这个widget, 最后打印这个widget.
现在遇到的问题是,发送的ajax请求, 后台获取到model怎么传给这个widget? 大概代码如下:


    function printBill(id) {
        $.ajax({
            type:'GET',
            url:"<?=\yii\helpers\Url::to(['sell/find-model'])?>" + "?id="+id,
            success:function (data) {
                
            }

        });
    }

...
    <?php
        Pjax::begin(['id'=>'printBill']);
        PrintBillWidget::begin(['model' => $model]);
        PrintBillWidget::end();
        Pjax::end();
    ?>

最佳答案

  • 师阳 发布于 2018-03-28 18:08 举报

    我觉得你可以把页面传进 widget 里,而不是把 model 传进去。或者不使用 widget。

    我提供一种解决方案。

    在 SellController.php 控制器里:

        public function actionPrint($id)
        {
            $this->layout = false;  //禁用布局
            $model = Sell::findOne($id);
            //这里需要补上其它代码,比如访问权限判断,找不到这个 model 等等。
            
            return $this->render('print', [
                'model' => $model,
            ]);
        }
    

    sell/print.php 视图中:

    <?= $model->title ?>
    <?= $model->content ?>
    

    以上我们完成了一些准备工作。这样以来,当我们通过 ajax 请求 sell/print 路由时,会返回 sell/print.php 这个视图,这个视图根据 model 来生成的发票内容,你自己再调整样式。

    然后,再其它你需要进行发票打印的地方。比如在某个 index.php 视图文件里,你加上如下代码:

    <?php
    use yii\bootstrap\Modal;
    ?>
    
    <script>
    function printBill(id) {
        $.ajax({
            type:'GET',
            url:"<?=\yii\helpers\Url::to(['sell/print'])?>" + "?id="+id,
            success:function(html){
                $('#solution-content').html(html);
                $('#solution').modal('show');
            }
        });
    }
    </script>
    <?php Modal::begin([
        'header' => '<h3>发票</h3>',
        'options' => ['id' => 'solution']
    ]); ?>
        <div id="solution-content">
        </div>
    <?php Modal::end(); ?>
    

    这样一来,当你调用 printBill(id) 时,会把

    <div id="solution-content">
        </div>
    

    这部分的内容替换成 sell/print.php 这个视图的内容。并通过 Modal 框显示出来(你也可以不用 Modal 框,我这只是举例)。核心还是在:

        $.ajax({
            type:'GET',
            url:"<?=\yii\helpers\Url::to(['sell/print'])?>" + "?id="+id,
            success:function(html){
                $('#solution-content').html(html); // 这里
            }
        });
    
    1 条回复
    回复于 2018-03-29 10:41 回复

    首先非常感谢你, 这么详细的回复. 这个方法很好用, 其实我一开始也没想封装widget, 就是没想到用AJAX请求,然后用html拼接的方式.还是基础知识不够扎实.

    没有找到数据。
您需要登录后才可以回答。登录 | 立即注册
秀小川
主管

秀小川

注册时间:2017-08-16
最后登录:2022-05-23
在线时长:20小时47分
  • 粉丝1
  • 金钱455
  • 威望0
  • 积分655

热门问题