Laravel如何在javascript上路由到路由


laravel how to route to a route on a javascript?

我有这个jquery

$(".waitingTime .button").click(function () {
    alert("Ema");
});

我有一个像这样的a标签:

<a href="{{ URL::to('restaurants/20') }}"></a>

我可以做同样的href在jquery功能的行动?

多谢

是的,这是可能的,与Laravel无关。有不同的可能性。如果您的查询嵌入在同一个laravel视图中,您可以将URL直接放入jQuery代码中,例如:

$(".waitingTime .button").click(function () {
  window.location.href = "{{URL::to('restaurants/20')}}"
});

但是我认为最好的选择是在你的按钮标签上添加URL作为数据属性,然后让jquery去那个URL。通过这种方式,您可以使按钮更加动态,代码更加紧凑。

例如:

<div class="waitingTime">
  <button class="button link-button" data-href="{{URL::to('restaurants/20')}}">
  Click me
  </button>
</div>
$(".link-button").click(function () {
  window.location.href = $(this).data('href');
});

这样你就可以给一个按钮类link-button一个data-href属性与URL,你想打开按钮时点击,而不必添加额外的jquery

在javascript中输出php

$(".waitingTime .button").click(function () {
    window.location.href = "<?php echo URL::to('restaurants/20'); ?>";
});

如果需要js中的变量可以使用

if(data.cookies == 0){
                  location.replace("{{ route('delivery') }}?id="+id);
                    }