[英]Add products to the cart jQuery/Ajax/Symfony/Twig
我在商店中使用 session 陣列作為購物車。 所以每次我將新產品添加到購物車時,我也會更新購物車的總價值,如下所示: <a class="navbar-brand px-3" href="{{path('checkout')}}" id="cart">Cart{{total}}€</a>
問題是每次我添加新產品時都會重新加載頁面,因為return $this->redirectToRoute('eshop');
在我的 add_product function 中。
我想添加產品並更新總值,而不重新加載整個頁面。 在這種情況下如何實現 jQuery 和 AJAX ? add_product function應該做哪些改變?
我試過這個,但產品沒有聲明為變量。
<script>
$(document).ready(function() {
$('#btnAddProduct').click(function() {
var pos = $('{{product.id}}').val();
$.ajax({
url: "{{path('add_product', {'id' : 'id'}) }}",
type: "POST",
data: },
success: function() {
}
});
});
});
我的產品看起來像這樣。
{% for product in products %}
<div class="col-lg-2">
<div class="card mb-3">
<img src="{{asset(product.image)}}" class="img-fluid" alt="{{product.name}}">
<h5 class="text-center" >{{product.name}}</h5>
<p class="text-center" >€{{product.price}}</p>
<form action="{{path('add_product', {'id' : product.id}) }}" method="post">
<button id="btnAddProduct" class="btn btn-primary btn-block" type="submit" >Add product</button>
</form>
</div>
</div>
{% endfor %}
還有我在 Symfony 中的 add_product 方法:
/**
* @Route("/eshop/add_product/{id}", name="add_product")
*/
public function add_product($id,Request $request){
$product = $this->eshop_model->get_product($id);
$total= $this->session->get('total');
$basket = $this->session->get('basket');
$check = 0;
foreach($basket as $k => $v){
if($v['id'] == $product['id']){
$basket[$k]['quantity']++;
$basket[$k]['subtotal'] += $product['price'];
$check = 1;
break;
}
}
if($check == 0){
$a = array('id' => $product['id'], 'quantity' => 1, 'subtotal' => $product['price'], 'price' => $product['price'], 'name' => $product['name']);
array_push($basket,$a);
}
$total= $total+ $product['price'];
$this->session->set('total',$total);
$this->session->set('basket',$basket);
return $this->redirectToRoute('eshop');
}
你的代碼庫的一個小例子。
首先刪除 Html 表單,並為您的產品 ID 添加一個數據字段到按鈕。
{% for product in products %}
<div class="col-lg-2">
<div class="card mb-3">
<img src="{{asset(product.image)}}" class="img-fluid" alt="{{product.name}}">
<h5 class="text-center" >{{product.name}}</h5>
<p class="text-center" >€{{product.price}}</p>
<button id="btnAddProduct" class="btn btn-primary btn-block" type="button" data-id="{{ product.id }}">Add product</button>
</div>
</div>
{% endfor %}
然后更改您的 controller class 以獲取正確的數據類型以使用 javascript 並為 id 添加默認值。
// Set id default value to get the route without id
/**
* @Route("/eshop/add_product/{id}", name="add_product")
*/
public function add_product(Request $request, $id = null): Response
{
// ..... your stuff
// remove
return $this->redirectToRoute('eshop');
// and add
return $this->json(['total' => $total]);
}
在您的總值周圍添加一個跨度標簽以將其設置為 javascript。
<a class="navbar-brand px-3" href="{{path('checkout')}}" id="cart">Cart <span id="total">{{ total }}</span>€</a>
將按鈕綁定到 ajax 調用並在成功時更改總字段。
$(document).ready(function() {
$('#btnAddProduct').click(function() {
$.ajax({
url: "{{ path('add_product') }}/" + $(this).data('id'),
type: "GET",
success: function(response) {
// Change #total text
$('#total').text(response.total);
}
});
});
});
就這樣;)
If you need both behaviours (default url with an redirect response and a json response for ajax calls), you can check if the request ist an ajax request.
public function add_product(Request $request, $id = null): Response
{
// ..... your stuff
if ($request->isXmlHttpRequest()) {
return $this->json(['total' => $total]);
}
return $this->redirectToRoute('eshop');
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.