[英]laravel5.2 convert laravel code to ajax
当我单击+时,此产品的数量增加1。
当我单击时-该产品的数量减少1。
cart.blade.php(查看):
<div class="cart_quantity_button">
<a class="cart_quantity_up" href='{{url("cart?product_id=$item->id&increment=1")}}'> + </a>
<input class="cart_quantity_input" type="text" name="quantity" value="{{$item->qty}}" autocomplete="off" size="2">
<a class="cart_quantity_down" href='{{url("cart?product_id=$item->id&decrease=1")}}'> - </a>
</div>
控制器中的购物车功能:
public function cart()
{
if (Request::isMethod('POST')) {
$product_id = Request::get('product_id');
$product = Product::find($product_id);
Cart::add(array('id' => $product_id,'name' => $product->name, 'qty' => 1, 'price' => $product->price,'options'=>array('image'=>$product->image)));
}
$id = Request::get('product_id');
//increment the quantity
if ($id && (Request::get('increment')) == 1) {
$p = Request::get('increment');
$rowId = Cart::search(array('id' => $id));
// echo "row id".$rowId."and the p=".$p;
$item = Cart::get($rowId[0]);
// echo "row id".$rowId;
$add = $item->qty + 1;
Cart::update($rowId[0], $add);
}
//decrease the quantity
if ($id && (Request::get('decrease')) == 1) {
$rowId = Cart::search(array('id' => $id));
$item = Cart::get($rowId[0]);
$sub = $item->qty - 1;
echo "item" . $sub;
Cart::update($rowId[0], $sub);
}
if ($id && (Request::get('remove')) == 1) {
$rowId = Cart::search(array('id' => $id));
Cart::remove($rowId[0]);
}
$cart = Cart::content();
return view('cart', array('cart' => $cart,'title' => 'Welcome', 'description' => '', 'page' => 'home','subscribe'=>"",'brands' => $this->brands));
}
public function cart_remove()
{
Cart::destroy();
return Redirect::away('cart');
}
public function checkout()
{
$cart = Cart::content();
return view('checkout', array('cart' => $cart,'title' => 'Welcome', 'description' => '', 'page' => 'home','subscribe'=>"",'brands' => $this->brands));
}
我想用ajax代码转换它,我为此做简单的代码
<script>
function getMessage($id)
{
$.ajax({
type: 'POST',
url: 'getmsg',
dataType: 'json',
data: {
valu_id: $id
},
success: function(data) {
$("#msg").html(data.msg);
}
});
}
</script>
<?php
$item_id = 3;
echo Form::button('+',['onClick'=>'getMessage($item_id)']);
?>
<div id='msg'>
<input id="msg" type="text" name="quantity" autocomplete="off" size="2">
</div>
控制器功能:
public function ajax()
{
$value= $_POST['valu_id']+1;
return response()->json(array('msg'=>$value), 200);
}
我不知道如何完成此代码。我对此代码有很多疑问。 喜欢
getmessage()
以在Ajax函数中使用它? getmessage()
放在<div class="cart_quantity_button">
而不是将按钮onclick
尊重上面的形状? 注意 :这个答案不只是为您提供有效的解决方案,还包括如何处理ajax请求/响应的想法。
首先,即使艰难的event.preventDefault()
也会阻止遵循URL的默认操作,我宁愿将URL存储到data-
attribute。
<div class="cart_quantity_button">
<a class="cart_quantity_up" href="javascript:void(0)" data-route="{{url('cart?product_id=$item->id&increment=1')}}"> + </a>
<input class="cart_quantity_input" type="text" name="quantity" value="{{$item->qty}}" autocomplete="off" size="2">
<a class="cart_quantity_down" href="javascript:void(0)" data-route="{{url('cart?product_id=$item->id&decrease=1')}}"> - </a>
</div>
如何从cart.blade.php视图获取产品ID并将其放在getmessage()中以在Ajax函数中使用它?
最好监听一个事件,在这种情况下是单击事件。
$('.cart_quantity_up').on('click', function(e) {
//an ajax call here
});
相同的代码适用于另一个
$('.cart_quantity_down').on('click', function(e) {
//an ajax call here
});
现在,两个单击事件已附加到每个对应的元素。 然后,是时候包装ajax函数了。
function updateQty(url){
var $qty = $('.cart_quantity_input');
$.ajax({
type: 'POST',
url: url,
dataType: 'json',
data: {
cart_qty: $qty.val()
},
success:function(data){
$qty.val(data.qty);
}
});
}
上面的功能很简单
cart_quantity_input
输入元素返回值为“ qty”的响应 然后,将ajax函数放在第一个代码段中(单击事件)
$('.cart_quantity_up').on('click', function(e) {
e.preventDefault();
//get the data-route
var url = $(this).data('route');
//call the ajax function
updateQty(url);
});
$('.cart_quantity_down').on('click', function(e) {
e.preventDefault();
//get the data-route
var url = $(this).data('route');
//call the ajax function
updateQty(url);
});
实际上,为了简化起见,您可以一次将来自多个选择器的事件附加在一起。
$('.cart_quantity_up, .cart_quantity_down').on('click', function(e) {
e.preventDefault();
//get the data-route for the 'up'
var url = $(this).data('route');
//call the ajax function
updateQty(url);
});
现在,您将获得有关如何创建ajax帖子并检索其响应以将其附加到输入元素的想法。
在这一点上,我将重构您的代码。 而且,您的所有问题都应该在此阶段得到回答。
在处理这种情况并收到这种简单情况的请求时,控制器看起来有些混乱。 我宁愿只是张贴。 不再有很多条件,我将足迹再次放在data-
attribute中。 最后,我将它们包装在一个表单中,因为CSRF令牌为您提供了更高的安全性。
<form name="cart_form">
{{ csrf_field() }}
<input type="hidden" class="item_id" value="{{ $item->id }}">
<div class="cart_quantity_button">
<button type="button" class="cart_quantity_up" data-route="{{url('cart')}}" data-increase="1"> + </button>
<input class="cart_quantity_input" type="text" name="quantity" value="{{$item->qty}}" autocomplete="off" size="2">
<button class="cart_quantity_down" data-route="{{url('cart')}}" data-increase="0"> - </button>
</div>
</form>
只要您要发布请求,就可以自由设计自己的视图(就像我正在做的那样)。 我将在逻辑上做一些解释。
$item->id
保留在隐藏字段中 url('cart')
路由发出ajax请求并将其存储到data-route
data-increase
以区分每个请求应该增加还是减少 现在听点击事件
$('.cart_quantity_up, .cart_quantity_down').on('click', function(e) {
e.preventDefault();
var $this = $(this),
url = $this.data('route'),
increase = $this.data('increase');
updateQty(url, increase);
});
在updateQty
函数下面与我updateQty
的第一个函数有些不同。 它接受第二个参数increase
作为(伪)布尔值。 还要注意,我将令牌发布为请求标头而不是正文。
function updateQty(url, increase){
var $qty = $('.cart_quantity_input'),
itemId = $('.item_id').val();
$.ajax({
type: 'POST',
url: url,
dataType: 'json',
headers: {
'X-CSRF-Token' : $('input[name="_token"]').val()
},
data: {
'cart_qty': $qty.val(),
'item_id': itemId,
'increase': increase
},
success:function(data){
$qty.val(data.qty);
}
});
}
您的控制器
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Cart;
use App\Http\Requests;
class YourController extends Controller
{
public function cart(Request $request)
{
if ($request->ajax()) {
$id = $request->item_id;
$cart = Cart::search(['id' => $id]);
//Note: This code may not working as what you expect
// but it should give you the idea that laravel
// actually has increment and decrement methods
// and else.
if ($request->increase) {
$cart->increment('qty');
} else {
$cart->decrement('qty');
}
$qty = $cart->first(['qty']);
return response()->json(['qty' => $qty]);
}
//rest is your code
//...
}
}
在上面的代码中,我试图
$_POST['increase']
更新qty
列
qty
列的值(尽管我不确定它是否会起作用) 'qty'
的值作为json $qty.val(data.qty)
更新您的输入元素
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.