javascript 从js文件调用laravel路由

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31072883/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 13:13:23  来源:igfitidea点击:

Call laravel route from js file

javascriptajaxlaravel-5

提问by newOne

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 :

我第一次使用 Laravel 5,当刀片调用 JS 文件时,我有一个刀片,其中包含一个 JS 文件。它无法识别 URL:这就是我在 JS 文件中调用我的 URL 的方式:

 $.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

当我在 myBlade.blade.php 中包含此代码时,它工作正常,但从 JS 文件中我收到了 403 错误

回答by sbedulin

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

Blade 不处理 JavaScript 文件,只处理带有blade.php扩展名的文件

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.phpplus main.js

假设您有两个单独的文件:index.blade.php加上main.js

1) index.blade.php

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

2) main.js

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

回答by Manmeet Khurana

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

在 Laravel 和 codeigniter 中,简单的方法是
获取 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) {
        ...
    }
});