我正在开发一个书店项目,可以将书籍添加到购物车,用户可以选择许多书籍将其添加到购物车。当用户单击按钮时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 调用,提前感谢任何帮助。
牧羊人nacy
拉风的咖菲猫
忽然笑