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

标签 php ajax laravel laravel-5 routes

我正在尝试将一个变量连接到我在 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 文件中。

最佳答案

Blade 服务器不存在$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.');
        }
    });

});

关于php - 如何在ajax URL路由中添加变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54994496/

相关文章:

php - 使用 PHP 将 MySQL 数据导出到 CSV 文件显示 1 行和空白 CSV

php - ajax 评级脚本 - 避免再次投票

c# - 更新面板的性质

mysql - 为什么 Laravel 在 DB::listen 后重定向到错误的 id?

php - MySQL "Convert"似乎无法正常工作

php - 有没有办法检测用户是否使用iphone 3GS或4浏览网站?

javascript - 无法通过ajax传递表单的输入值

javascript - 自动完成搜索从服务器检索数据花费的时间太长

php - 无法从多个 html 复选框访问值

php - 在 Laravel 4 中搜索和过滤/精炼数据库结果