我正在尝试添加一些功能,用户可以在不使用Ajax刷新页面的情况下将项目添加到购物车中。我成功地将数据发布到数据库中,但无法自动刷新列表(在发布数据后(。
Ajax
jQuery(document).ready(function(){
jQuery("#addtocartt{{$one->id}}").on('click',function(e){
e.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
jQuery.ajax({
url: "/addtocart",
method: 'post',
data: {
data: jQuery("#name{{$one->id}}").val(),
image: jQuery("#image{{$one->id}}").val(),
price: jQuery("#price{{$one->id}}").val(),
quantity: jQuery("#quantity{{$one->id}}").val(),
},
success: function(result){
var xs = result.qte;
swal(xs+"Kgs of {{$one->name}}", "Is Added to Cart !!", "success");
}});
});
});
这是我想要刷新的列表。
@foreach($list as $one)
<text style="font-family: Poppins-ExtraLight;"> {{$one->cart_item}} : {{$one->quantity}} x {{$one->cart_price}} dh = {{$one->quantity*$one->cart_price}}</text> <br>
@endforeach
控制器
function Add(Request $request){
$item = new cart;
$item->user_id = Auth::user()->id;
$item->cart_number = '0';
$item->cart_item = $request->data;
$item->quantity = $request->quantity;
$item->cart_price = $request->price;
$item->image = $request->image;
$item->save();
$list= cart::all()->where('user_id',Auth::user()->id)->where('state','=','delivering');
return response()->json(['qte' => $item->quantity]);
}
我还没有对此进行测试,但假设$list
变量返回cart,则可以执行以下操作:
您的刀片模板
<div id="some-list-container">
@foreach($list as $one)
<text style="font-family: Poppins-ExtraLight;"> {{$one->cart_item}} : {{$one->quantity}} x {{$one->cart_price}} dh = {{$one->quantity*$one->cart_price}}</text> <br>
@endforeach
</div>
您的控制器
return response()->json(['list' => $list, 'item' => $item]);
您的Javascript
...
success: function(result) {
var item = result.item;
var list = result.list;
swal(item.quantity + "Kgs of " + item.name, "Is Added to Cart !!", "success");
// clear the list
jQuery("#some-list-container").empty()
// loop through the response list
for(var i=0; i < list.length; i++) {
// add to the list
var add_item = list[i];
jQuery("#some-list-container").append('<text style="font-family: Poppins-ExtraLight;"> '
+ add_item.cart_item + ' : '
+ add_item.quantity + ' x '
+ add_item.cart_price + ' dh = '
+ (add_item.quantity * add_item.cart_price)
+ '</text> <br>')
}
}
...
希望这能让你走上正确的道路