简体   繁体   English

Laravel ajax 发布数据

[英]Laravel ajax post data

I have an eCommerce shop where I have to filter products by its categories.我有一家电子商务商店,我必须按类别过滤产品。

I have to post an array of all filters in the controller, but I am getting this error我必须在 controller 中发布所有过滤器的数组,但我收到此错误

 "message": "",
    "exception": "Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException",
    "file": "C:\\xampp\\htdocs\\web_front\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\RouteCollection.php",
    "line": 179

Here is my code:这是我的代码:

 <script>
    $(document).ready(function () {
        var categories = [];
        $('input[name="cat[]"]').on('change', function (e) {
            e.preventDefault();
            categories = []; // reset
            $('input[name="cat[]"]:checked').each(function()
            {
                categories.push($(this).val());
            });



            $.ajax({

                type:"GET",

                url:'advanced_filter/' + categories,


                success:function(data){

                    console.log(data);
                },
                error: function(xhr,errmsg,err)
                {
                    console.log(xhr.responseText);
                }
            });
        });
    });

</script>

web.php web.php

Route::get('advanced_filter/{filters}', 'HomepageController@advanced_filter')->name('advanced_filter');


 public function advanced_filter($filters)
    {
dd($filters);
}

I am trying to show all the filters, so I can make a query to get all the products based on filters.我正在尝试显示所有过滤器,因此我可以进行查询以获取基于过滤器的所有产品。 I have created the script where I get all filters and want to post it in the controller.我创建了获取所有过滤器的脚本,并希望将其发布在 controller 中。 Please, can you see this?请问,你能看到这个吗? Thank you谢谢

first of all:首先:

"exception":"Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException",

above exeption occur when route is not found.找不到路由时会发生上述异常。 NotFoundHttpException has status 404 NotFoundHttpException 的状态为 404

in your code you are passing array of categories in route params, which is syntactically wrong, so thats why failed to find route.在您的代码中,您在路由参数中传递了类别数组,这在语法上是错误的,所以这就是为什么找不到路由的原因。

Route::get('advanced_filter', 'HomepageController@advanced_filter')->name('advanced_filter');

from frontend side: pass categories as query parameters从前端:将类别作为查询参数传递

url will be: url 将是:

/advanced_filter?queryParameter= ids of selected categories /advanced_filter?queryParameter= 所选类别的 ID

/advanced_filter?categories=1,3,7

your ajax function will be:您的 ajax function 将是:

$.ajax({
     type:"GET",
     url:`/advanced_filter?categories=${categories.join(',')}`,
     success:function(data){
             console.log(data);
      },
      error: function(xhr,errmsg,err){
             console.log(xhr.responseText);
      }
   });

in your controller:在您的 controller 中:

use Illuminate\Http\Request;

public function advanced_filter(Request $request)
{
    $filter_categories=[];
    if($request->has('categories')){
      $filter_categories=$request->query('categories');
    }

    /* you can pass extra query parameter like sortBy,sortOrder,limit  in url 
     `/advanced_filter?categories=1,3,7&limit=24&sortBy=name&sortOrder=desc`
 */

     $sortBy=$request->has('sortBy')?$request->query('sortBy'):'id';
     $sortOrder=$request->has('sortOrder')?$request->query('sortOrder'):'desc';
     $limit = $request->has('limit')?$request->has('limit'):12;

     /* assuming you have models with relations */

     $query = Products::query();
     $query->with('categories');
     if(count($filter_categories)>0){
        $query->whereHas('categories', function ($q) use ($filter_categories) {
            $q->whereIn('categories.id',$filter_categories);
        });
     }
     $query->orderBy($sortBy,$sortOrder);
     $products = $query->paginate($limit);
     return response()->json($products);

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM