Laravel Passing route to js

只谈情不闲聊 提交于 2021-02-10 20:44:03

问题


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

})

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


回答1:


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"/>

Then, in file.js, reference the variable:

...
url: url,
...


来源:https://stackoverflow.com/questions/59994319/laravel-passing-route-to-js

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