如何在ajax调用时从laravel控制器函数返回视图?

Abd*_*ani 7 javascript php ajax laravel

我正在做一个书店项目,可以将书籍添加到购物车,用户可以选择许多书籍将它们添加到购物车。当用户单击Add to Cart按钮时,我将所选书籍的 ID 添加到名为 .js 的 JS 数组中cart。当所有选定的书都添加到购物车后,我想<a>用 ajax 调用链接标签,该调用将命中控制器函数的 url 并发送 JScart数组对象发送到控制器函数,然后在控制器函数中,我想返回查看浏览器,我不希望控制器函数将响应返回给 ajax 调用,而是我想将视图返回给浏览器。

这是将所选书籍的 ID 添加到cartJS 数组的 JS 函数:

function addToCart(id)
{
if(! cart.includes(id) ) cart.push(id);

cartLength.html(cart.length);
$('#successCart'+id).html('Book added to cart.');

}  
Run Code Online (Sandbox Code Playgroud)

这里是<a>调用ajax函数的标签,函数名是showCart():

<a href="#" onclick="event.preventDefault(); showCart();">
  <i class="fa fa-shopping-cart"></i>
  <span id="cartLength"></span>
</a>  
Run Code Online (Sandbox Code Playgroud)

这是showCart()具有ajax代码的函数:

function showCart()
{


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

$.ajax({
        url:"cart",
        method:'post',
        data:{cart:cart},
        dataType: 'html'
  })
 .done(function(msg){


  });
 .fail(function(msg){
    alert(msg.responseJSON.errors);
 });
}  
Run Code Online (Sandbox Code Playgroud)

这是控制器函数 - 我希望这个函数直接将视图返回给浏览器,而不将它发送回 ajax 调用:

public function showCart(Request $request)
{
    return view('cart', ['cart' => $request->cart ]); // this should be returned to the browser and not to the ajax call
}  
Run Code Online (Sandbox Code Playgroud)

这是控制器功能的路线:

Route::post('/cart', 'HomeController@showCart')->name('home.cart');  
Run Code Online (Sandbox Code Playgroud)

编辑:

我用以下技巧暂时解决了这个问题,但这不是永久的解决方案:

在调用showCart()函数 fromajax以将cart数组变量发送jslaravel控制器后,我使用以下逻辑将书籍ids存储在存储在cart数组中的会话变量中:

public function showCart(Request $request)
{

    session()->put('cart_books', Book::whereIn('id', $request->cart)->get()); 
    session()->save();
    return "success";

}  
Run Code Online (Sandbox Code Playgroud)

将查询结果存储在会话变量中后,我创建了另一个GET路由,/cart如下所示:

Route::get('/cart', 'HomeController@viewCart');  
Run Code Online (Sandbox Code Playgroud)

然后在postajax 调用成功后,我/cart使用get如下方法调用:

.done(function(msg){
    console.log('calling cart');
    location.href = "cart"; // Here I call the `/cart` with `get` method which will hit the `viewCart()` function of HomeController which will return the view back to the browser along with the results that were stored in the session variable.

  })  
Run Code Online (Sandbox Code Playgroud)

这是将viewCart()视图返回给浏览器并将会话变量的数据发送到视图的控制器函数:

public function viewCart()
{
   $random_books = Book::all()->random(4);
   $categories = Category::all();
    return view('cart', ['cart_books' => session()->get('cart_books'), 
  'random_books' => $random_books, 'categories' => $categories]); 
}
Run Code Online (Sandbox Code Playgroud)

我希望控制器函数将视图返回到浏览器而不将其返回到 ajax 调用,任何帮助都提前表示赞赏。

Abd*_*san 0

在控制器函数中只需添加渲染方法,如下所示

public function showCart(Request $request)
{
   return view('cart', ['cart' => $request->cart ])->render();
}  
Run Code Online (Sandbox Code Playgroud)

对于js:

$.ajax({
method: 'POST', // Type of response and matches what we said in the route
url: '{{ route('home.cart') }}', // This is the url we gave in the route
data: {'cart' : cart}, // <-- this is your POST data
success: function(response){ // What to do if we succeed
    console.log(response);
},
error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
    console.log(JSON.stringify(jqXHR));
    console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
Run Code Online (Sandbox Code Playgroud)