如何在ajax URL路由中添加变量

Eem*_*Jee 3 php ajax routes laravel laravel-5

我正在尝试将变量连接到 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.');
        }
    });

});
Run Code Online (Sandbox Code Playgroud)

在我的 web.php 中,它的路由位于路由组内。

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

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

Jos*_*tto 5

$news 对于 Blade 来说并不存在,因为它在服务器渲染页面的时间上执行。所以你的 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.');
        }
    });

});
Run Code Online (Sandbox Code Playgroud)