最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Call laravel route from js file - Stack Overflow

programmeradmin2浏览0评论

I'm working with Laravel 5 for the first time, i have a blade where i include a JS file, when the blade calls the JS file. It doesn't recognize the URL : this is how i call my URL in JS file :

 $.ajax({
        type: "POST",
        cache: false,
        url : "{{URL::to('zone')}}",
        data: {'ma':$('select[name=ma]').val()},
        success: function(data) {
            ...
        }
    });

When i include this code in myBlade.blade.php it works fine but from the JS file i got the 403 error

I'm working with Laravel 5 for the first time, i have a blade where i include a JS file, when the blade calls the JS file. It doesn't recognize the URL : this is how i call my URL in JS file :

 $.ajax({
        type: "POST",
        cache: false,
        url : "{{URL::to('zone')}}",
        data: {'ma':$('select[name=ma]').val()},
        success: function(data) {
            ...
        }
    });

When i include this code in myBlade.blade.php it works fine but from the JS file i got the 403 error

Share Improve this question asked Jun 26, 2015 at 12:11 newOnenewOne 211 gold badge1 silver badge2 bronze badges 0
Add a comment  | 

2 Answers 2

Reset to default 18

Blade doen't process JavaScript files, only those with blade.php extension

Solution may be to provide a global configuration object with a collection of routes you are interested in.

Assuming you have two separate files: index.blade.php plus main.js

1) index.blade.php

<script>
    // global app configuration object
    var config = {
        routes: {
            zone: "{{ URL::to('zone') }}"
        }
    };
</script>
<script src="main.js"></script>

2) main.js

$.ajax({
    type: "POST",
    cache: false,
    url : config.routes.zone,
    data: {'ma':$('select[name=ma]').val()},
    success: function(data) {
        ...
    }
});

In Laravel And Also In codeigniter simple Approch is
get the Base Url Path
Here I user

//code here
var path = {!! json_encode(url('/')) !!}

$.ajax({
    type: "POST",
    cache: false,
    url : path+'/zone',
    data: {'ma':$('select[name=ma]').val()},
    success: function(data) {
        ...
    }
});
发布评论

评论列表(0)

  1. 暂无评论