【问题标题】:loading url to bootstrap modal using ajax in Laravel not working在 Laravel 中使用 ajax 将 url 加载到引导模式不起作用
【发布时间】:2020-07-15 21:19:31
【问题描述】:

在 Laravel 中 -Controller 名称是 ProductController,方法是 showproductinmodal 。 我试过这个,它工作的javascript代码。

网络路由:

Route::get('admin/product/show/{id}', 'Admin\ProductController@showproductinmodal');

JS:

<script>
            $('.showinfo').click(function(){

            var productid = $(this).data('id');

            // AJAX request
            $(".modal-body").load("{{URL::to('admin/product/show/')}}"+"/"+productid);


            });            
</script>

Url 加载并返回一些文本到模态。 但是这段 Javascript 代码不起作用,我想使用下面的代码:

$(document).ready(function(){

 $('.showinfo').click(function(){

   var productid = $(this).data('id');

   // AJAX request
   $.ajax({
    url: '{{route('admin.showproductinmodal')}}',
    type: 'post',
    data: {id: productid},
    success: function(response){ 
      // Add response in Modal body
      $('.modal-body').html(response);

    }
  });
 });
});

我的网络路由代码

Route::post('admin/product/show/', 'Admin\ProductController@showproductinmodal')->name('admin.showproductinmodal');

我的控制器代码:

public function showproductinmodal(Request $id)
    {
        return "Your test id:" . $id;
    }

我的标签

<a  href="#" data-toggle="modal" data-target="#modaldemo3"  data-id="15" class="showinfo">Any ID test</a>

Modal 工作正常,当我使用第一个 javascript 代码时弹出一切正常数据加载,但第二个 javascript 代码对我来说是必要的。我也在 $.ajax 请求中插入了警报,但它不起作用。

【问题讨论】:

    标签: php jquery html ajax laravel


    【解决方案1】:

    您可能缺少 crsf 令牌:

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    

    为ajax调用设置csrf令牌一次,然后调用N个ajax:

    $(document).ready(function () {
        $('.showinfo').click(function () {
            var productid = $(this).data('id');
            let url = "{!! route('admin.showproductinmodal') !!}"
            // AJAX request
            $.ajax({
                url: url,
                type: 'post',
                data: { 
                    id: productid 
                },
                success: function (response) {
                    // Add response in Modal body
                    $('.modal-body').html(response);
                }
            });
        });
    });
    

    如果您将使用引导模型事件,并使用带有 javascript 全局变量的基本 url,它会更好。

    【讨论】:

      猜你喜欢
      • 2016-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-31
      • 1970-01-01
      • 2015-12-11
      • 2016-07-07
      • 2015-11-14
      相关资源
      最近更新 更多