【问题标题】:Can't get any data in controller that sent from ajax无法在控制器中获取从 ajax 发送的任何数据
【发布时间】:2020-09-24 16:57:25
【问题描述】:

我有一条路线,

Route::post('/shop', 'ShopController@index');
Route::resource('/shop', 'ShopController')->parameters(['shop' => 'slug']);

我想通过价格范围过滤产品。

这是我的:

filter_data();
        var sliderrange = $('#slider-range');
        var amountprice = $('#amount');
        function filter_data() {
            var  min_price = $("#min_price").val();
            var  max_price = $("#max_price").val();
            console.log(min_price);
            $.ajax({ url:"/shop", method:"POST",
                data:{ min_price:min_price, max_price:max_price,},
                success:function (data) { },
            });
        };

这是控制器:

    public function index(Request $request)
{
    $data = $request->input('min_price');
    print_r($data);

}

在视图中这是返回一个空数组。

【问题讨论】:

    标签: javascript php mysql ajax laravel


    【解决方案1】:

    你已经调用了两个帖子方法,网址是 /shop

    Route::post('/shop', 'ShopController@index'); // this is method index
    Route::resource('/shop', 'ShopController') //this called store method.
    

    所以当你调用/shop 方法时,它会调用 ShopController 的 store 方法。

    删除Route::post('/shop', 'ShopController@index');并使用store方法。

     public function store(Request $request)
    {
        $data = $request->input('min_price');
        print_r($data);
    
    }
    

    【讨论】:

      【解决方案2】:

      此方法用于获取所有数据

         public function index(Request $request)
          {
              $data = $request->all();
              print_r($data);
      
          }
      

      【讨论】:

      • 给我一个空数组
      【解决方案3】:

      在 Js 中:

        var  min_price = $("#min_price").val();
          var  max_price = $("#max_price").val();
          $.ajax({
              url:"/shop_get",
              method:"POST",
              data:{
                "min_price":min_price,
                "max_price":max_price,
                "_token":"{{csrf_token()}}"
              },
              success:function(response){
                   console.log(response);
              },
             error:function(errors){
                   console.log(errors);
              }
          });
      

      在控制器中:

      public function index(Request $request)
          {
              echo "<pre>";
              print_r($request->all());
      
          }
      

      在路线中:

      Route::post('/shop_get', 'ShopController@index');
      

      【讨论】:

        猜你喜欢
        • 2020-09-24
        • 1970-01-01
        • 2021-08-19
        • 2021-09-30
        • 1970-01-01
        • 1970-01-01
        • 2016-11-15
        • 1970-01-01
        • 2018-06-05
        相关资源
        最近更新 更多