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

我正在开发一个书店项目,可以将书籍添加到购物车,用户可以选择许多书籍将其添加到购物车。当用户单击按钮时Add to Cart,我将所选书籍的 ID 添加到名为 的 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.');


}  

下面是<a>调用ajax函数的标签,函数名为showCart():


<a href="#" onclick="event.preventDefault(); showCart();">

  <i class="fa fa-shopping-cart"></i>

  <span id="cartLength"></span>

</a>  

这是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);

 });

}  

这是控制器函数 - 我希望此函数直接将视图返回到浏览器,而不将其发送回 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

}  

这是控制器功能的路线:


Route::post('/cart', 'HomeController@showCart')->name('home.cart');  

编辑:


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


调用showCart()函数将数组变量ajax发送到控制器后,我使用以下逻辑将书籍存储在会话变量中,该会话变量存储在数组中:cartjslaravelidscart


public function showCart(Request $request)

{


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

    session()->save();

    return "success";


}  

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


Route::get('/cart', 'HomeController@viewCart');  

然后在ajax调用成功后post,我用/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.


  })  


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


慕妹3146593
浏览 132回答 3
3回答

牧羊人nacy

您可以通过渲染并返回控制器内的视图来从 ajax 调用返回原始 html,如下所示:return&nbsp;view('cart',&nbsp;['cart'&nbsp;=>&nbsp;$request->cart])->render();这将返回原始 HTML,您可以进一步使用它。但是,从ajax返回HTML并不是一个好方法,您可以从控制器返回JSON并根据JSON数据在前端渲染视图。

拉风的咖菲猫

正如其他人所说,你可以使用return view('cart', ['cart' => $request->cart])->render();在你的 jQuery 中做.done(function(response){&nbsp; &nbsp; document.write(response);});或者您可以返回应向用户显示其内容的链接,并在完成方法中重定向用户。所以在你的后端你会有return route('cart', ['cart' => $request->cart]);在你的前端你会有.done(function(response){&nbsp; &nbsp; location.href = response;});

忽然笑

在控制器函数中只需添加渲染方法,如下所示public function showCart(Request $request){&nbsp; &nbsp;return view('cart', ['cart' => $request->cart ])->render();}&nbsp;&nbsp;对于js:$.ajax({method: 'POST', // Type of response and matches what we said in the routeurl: '{{ route('home.cart') }}', // This is the url we gave in the routedata: {'cart' : cart}, // <-- this is your POST datasuccess: function(response){ // What to do if we succeed&nbsp; &nbsp; console.log(response);},error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail&nbsp; &nbsp; console.log(JSON.stringify(jqXHR));&nbsp; &nbsp; console.log("AJAX error: " + textStatus + ' : ' + errorThrown);}});
打开App,查看更多内容
随时随地看视频慕课网APP