php laravel 如何路由到 javascript 上的路由?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24353736/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 17:17:19  来源:igfitidea点击:

laravel how to route to a route on a javascript?

phplaravellaravel-4blade

提问by Anastasie Laurent

I have this jquery

我有这个 jquery

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

I have a atag like this:

我有一个a这样的标签:

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

Can I do the same hrefaction in the jquery function?

我可以href在 jquery 函数中执行相同的操作吗?

Many Thanks

非常感谢

回答by Matthias S

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:

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

$(".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.

但我认为最好的选择是在按钮标签上添加 URL 作为数据属性,然后让 jquery 转到该 URL。这样你就可以让你的按钮更加动态并拥有更多的封装代码。

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-buttona data-hrefattribute with the URL you want to open when the button is clicked and don't have to add additional jquery.

这样,您始终可以为该类的按钮提供link-button一个data-href属性,其中包含您要在单击按钮时打开的 URL,而不必添加额外的 jquery。

回答by Krimson

Just output php in your javascript

只需在您的 javascript 中输出 php

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