Laravel将路线传递给js [英] Laravel Passing route to js
问题描述
我在laravel公共文件夹中有一个单独的js文件,我已经取消了进入web.php的路线,我可以在刀片文件中使用它们,但是在尝试在该js文件中使用它们时出错.
I have a separate js file into laravel public folder, I have decleard my route into web.php, I can use them in blade file but getting error while try to use them in that js file.
$.ajax({
//url:"http://127.0.0.1:8000/cats/fetch",
url:"{{route('cats.fetch')}}",
method:"POST",
data:{select:select, value:value, _token:_token, dependent:dependent},
success:function(result)
{
$('#'+dependent).html(result);
}
})
但是当我使用硬编码的url时,它的工作例如url:"cats/fetch".如何使它可配置,而不是硬编码到js文件中
but when I use hard coded url then its work for instance url:"cats/fetch". How can I make it configurable not hard coded into js file
推荐答案
url:"{{route('cats.fetch')}}""
无效 .js
语法.您是正确的,可以在 .blade.php
中使用它,但是在外部 .js
文件中,需要首先将其分配给变量:
url:"{{route('cats.fetch')}}",
is not valid .js
syntax. You're correct that you can use it in .blade.php
, but in an external .js
file, you need to assign it to a variable first:
<script type="text/javascript">
let url = "{{ route('cats.fetch') }}";
</script>
<script src="path/to/file.js" type="text/javascript"/>
然后在 file.js
中引用变量:
...
url: url,
...
这篇关于Laravel将路线传递给js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!