doukanwa6872 2016-06-06 09:39
浏览 226

YII2。 在js中使用URL

I have the following javascript code

$(".order-event-btn").click(function(e) {
$.ajax({
url: "URL",
type: "POST",
data: {
    eventId: $(e.target).attr('data-event-id'),
},
success: function(data) {
    //Some code
},
error: function(data) {
    //Some code
},
});
});

I include this script using "BookAsset".

Here

url: "URL",

I need URL to the action "book-event" in the controller Book.

On the server, I can do this:

 Url::to('/book/book-event')

But how do I get URL on client side?

There is an solution:

1. js file include via BookAsset.

2. in view file I register bundle:

\frontend\assets\BookAsset::register($this);

3. in view file define a bookEventURL variable. Now it is available in the js-file.

$this->registerJs('var bookEventURL = ' . Url::to('/book/book-event') . ';');

But I do not like this solution. What will happen when I use this script in many views. I have to define a variable bookEventURL in each view?

My Question. Is it possible to bind js-variables to my BookAsset. When I register my BookAsset in the view, in page source code automatically insert next code:

<script>var bookEventURL = "http://example.com/book-event/";</script>
  • 写回答

2条回答 默认 最新

  • doujiu6976 2016-06-06 09:59
    关注

    A proper way of doing this is to add the needed information in your button tag, e.g. :

    <?= Button::widget([
        'label' => 'Order',
        'options' => [
            'class' => 'order-event-btn',
            'data' => [
                'url' => Url::to(['book/book-event']),
            ],
        ],
    ]) ?>
    

    And in your js code :

    $(".order-event-btn").click(function(e) {
        var url = $(this).data('url');
        // ...
    });
    

    But if you really want to "bind js-variables" to your BookAsset, you could simply override register() :

    public static function register($view)
    {
        parent::register($view);
        $view->registerJs('var bookEventURL = ' . json_encode(Url::to(['book/book-event'])) . ';');
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向