简体   繁体   English

Laravel Ajax无法在url中传递参数,但可以使用常量

[英]Laravel Ajax can't pass parameter in url but works with a constant

I'm writing an ajax that works when url contains a constant but does not work when url contains a variable because this does not get replaced by the actual value. 我正在写一个ajax,它在url包含常量时起作用,而在url包含变量时不起作用,因为它不会被实际值替换。

$('body').on('click', '.deleteLayer', function () {
        var layer_id = $(this).data('id');
        confirm("Are You sure want to delete record with layer_id="+layer_id+"?");

        $.ajax({
            type: "POST",
            url: "{{ route('layers.destroy',['layer' => "+layer_id+"])}}",
            data: {_method: 'delete', layer:layer_id},
            success: function (data) {
                table.draw();
            },
            error: function (data) {
                console.log('Error:', data);
            }
        });
    });

  });

If I use a value, let's say 50 instead of layer_id then it works!!!: 如果我使用一个值,那么说50而不是layer_id,那么它可以工作!

 url: "{{ route('layers.destroy',['layer' => 50])}}",

This is the route that I try to access: 这是我尝试访问的路由:

DELETE | admin/layers/{layer} | layers.destroy   

If I do not send layer parameter in the url I receive the following error 如果我未在网址中发送图层参数,则会收到以下错误

message : "Missing required parameters for [Route: layers.destroy] [URI: admin/layers/{layer}]. (View: /var/www/laravelapp/resources/views/layers.blade.php)" 消息:“缺少[路由:layers.destroy] [URI:admin / layers / {layer}]所需的参数。(查看:/var/www/laravelapp/resources/views/layers.blade.php)”

Why is layer_id, here 为什么是layer_id,在这里

 url: "{{ route('layers.destroy',['layer' => "+layer_id+"])}}", 

not replaced by the actual value? 不能用实际值代替吗?

When you are writing like ['layer' => "+layer_id+"] the js variable is not working. 当您像['layer' => "+layer_id+"]一样书写时,js变量不起作用。 It goes like +layer_id+ as the parameter of the route. 它类似于+layer_id+作为路由的参数。 You can try like this 你可以这样尝试

var layer_id = $(this).data('id');
var url = '{{ route("layers.destroy", ":id") }}';
url = url.replace(':id', layer_id );
$.ajax({
    type: "POST",
    url: url,
    data: {},
    success: function (data) {

    },
    error: function (data) {

    }
});
{{URL::to('/destroy')}}+'/'+layer_id;

Route 路线

Route::get('/destroy/{id}', 'controller@destroy')

Controller 控制者

public function destroy($id){
// use $id here

} }

Hope you understand. 希望你能理解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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