问题
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