laravel how to route to a route on a javascript?

ぐ巨炮叔叔 提交于 2019-12-07 05:24:04

问题


I have this jquery

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

I have a a tag like this:

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

Can I do the same href action in the jquery function?

Many Thanks


回答1:


yes this is possible and has nothing to do with Laravel. There are different possibilities. If your query is embedded within the same laravel view, you put the URL directly in your jQuery code, for example like this:

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

But I think the best option is to add the URL on your button tag as a data attribute and then let jquery go to that URL. That way you can make your buttons more dynamic and have more capsulated code.

One example might be:

<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');
});

That way you can always give a button with the class link-button a data-href attribute with the URL you want to open when the button is clicked and don't have to add additional jquery.




回答2:


Just output php in your javascript

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


来源:https://stackoverflow.com/questions/24353736/laravel-how-to-route-to-a-route-on-a-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!