简体   繁体   中英

linking external javascript in laravel not working

Does the way you add an external js link to a laravel application differs to how you add a css . I ask because I've been able to successfully add a css external file like this:

<link rel="stylesheet" type="text/css" href="{{asset('css/custom.css')}}"/>

When i do this however :

<script src="{{asset('js/autocomplete1.js')}}"></script>

On the console i get a 404 error that:

GET http://spanibox.com/%7B%7B%20route('searchajax')%20%7D%7D?term=a&type=EmpService 404 (Not Found)

2 things to consider when you try to answer:

  1. This works if i simply write up the javascript within my blade view

2.Not sure if this will be relevant but On firefox there us a warning:

Content Security Policy: Ignoring “'unsafe-inline'” within script-src: ‘strict-dynamic’ specified

It does not work because you are trying to use blade syntax within your JS file. In your URL you have this {{ route('searchajax') }} which is a blade syntax and JS does not know how to evaluate it.

You can create a global object that will hold your routes or translations. In your main blade file, in the head you can add this:

<script>

    window.MY_PROJECT = {
        search_ajax: "{{ route('searchajax') }}";
    };

</script>

Then in your JS file use it like this:

MY_PROJECT.search_ajax // prints out your URL

Try putting the <script src="{{asset('js/autocomplete1.js')}}"></script> just before your </body> . (Note: This may not work depending on what your script is doing.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM