【问题标题】:How to add a variable in ajax URL route如何在 ajax URL 路由中添加变量
【发布时间】:2019-07-26 10:18:57
【问题描述】:

我正在尝试将一个变量连接到我在 ajax 中的 url 链接。变量$news 是处理通知ID 的变量。

$(document).on("click", "#viewList", function() {

    $.ajaxSetup({
        headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    var $news = $(this).prop("value");
    $.ajax({
        type: "get",
        url : '{{url("admin/recipients/", $news)}}', //returning an error undefined variable news
        data: {newsID : $news},
        success: function(store) {
            console.log(store);
            $('#rec').text(store);
        },
        error: function() {
          $('.alert').html('Error occured. Please try again.');
        }
    });

});

在我的 web.php 中,它的路由在一个路由组内。

Route::group(['middleware' => 'auth:admin'], function () {
    Route::prefix('admin')->group(function() {
        Route::get('/recipients/{news}', 'Admin\NewsController@recipients');
    });
});

那么我怎样才能做到这一点呢?顺便说一句,我的 ajax 在 blade.php 文件中。

【问题讨论】:

    标签: php ajax laravel laravel-5 routes


    【解决方案1】:

    $news 对刀片不存在,因为它在服务器呈现页面的时间执行。所以你的javascript还没有被执行。为了使这项工作,将您的 js 代码更改为:

    $(document).on("click", "#viewList", function() {
    
        $.ajaxSetup({
            headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
        var news = $(this).prop("value");
        $.ajax({
            type: "get",
            url : '{{url("admin/recipients")}}' + '/' + news,
            data: {newsID : news},
            success: function(store) {
                console.log(store);
                $('#rec').text(store);
            },
            error: function() {
              $('.alert').html('Error occured. Please try again.');
            }
        });
    
    });
    

    【讨论】:

    • 错误:GET https://localhost/admin/recipients12?newsID=12 404 (Not Found) 它应该是'localhost/admin/recipients/12?newsID=12'。缺少/
    • 是的,你必须在你的 js 中添加这个,所以你必须使用'{{url("admin/recipients")}}' + '/' + news 而不是'{{url("admin/recipients/")}}' + news。我猜是因为 url Blade 功能正在删除最后一个 /
    猜你喜欢
    • 2012-12-12
    • 2021-03-03
    • 1970-01-01
    • 1970-01-01
    • 2017-09-11
    • 1970-01-01
    • 2020-02-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多