亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 ajax 調用時從 laravel 控制器函數返回視圖?

如何在 ajax 調用時從 laravel 控制器函數返回視圖?

PHP
慕妹3146593 2023-09-15 10:19:39
我正在開發一個書店項目,可以將書籍添加到購物車,用戶可以選擇許多書籍將其添加到購物車。當用戶單擊按鈕時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發送到控制器后,我使用以下邏輯將書籍存儲在會話變量中,該會話變量存儲在數組中:cartjslaravelidscartpublic 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 調用,提前感謝任何幫助。
查看完整描述

3 回答

?
牧羊人nacy

TA貢獻1862條經驗 獲得超7個贊

您可以通過渲染并返回控制器內的視圖來從 ajax 調用返回原始 html,如下所示:

return view('cart', ['cart' => $request->cart])->render();

這將返回原始 HTML,您可以進一步使用它。但是,從ajax返回HTML并不是一個好方法,您可以從控制器返回JSON并根據JSON數據在前端渲染視圖。


查看完整回答
反對 回復 2023-09-15
?
拉風的咖菲貓

TA貢獻1995條經驗 獲得超2個贊

正如其他人所說,你可以使用


return view('cart', ['cart' => $request->cart])->render();

在你的 jQuery 中做


.done(function(response){

    document.write(response);

});

或者您可以返回應向用戶顯示其內容的鏈接,并在完成方法中重定向用戶。所以在你的后端你會有


return route('cart', ['cart' => $request->cart]);

在你的前端你會有


.done(function(response){

    location.href = response;

});


查看完整回答
反對 回復 2023-09-15
?
忽然笑

TA貢獻1806條經驗 獲得超5個贊

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


public function showCart(Request $request)

{

   return view('cart', ['cart' => $request->cart ])->render();

}  

對于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);

}

});


查看完整回答
反對 回復 2023-09-15
  • 3 回答
  • 0 關注
  • 163 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號