2015-04-23 76 views
1

當我展示中保存的會議我有一個按鈕與我想刪除一個特定的產品,如果我不需要它選擇的產品。我可以用javascript實現嗎?如果不是什麼解決這個問題的其他解決方案?Symfony2是否可以使用Javascript刪除會話變量?

我聽說你不能設置會話變量與JavaScript所以可能是相同的去與中刪除,但我聽說,你可以做一些與阿賈克斯將其刪除?反正即時顯示我的同類產品(現在我只是在展示產品的價格動態):

{% for item in items %} 
    <tr> 
     <td><img width="60" src="{{ asset('bundles/mpFrontend/assets/products/4.jpg') }}" alt=""/></td> 

     <td>{{ item.model }}</td> 
     <td> 
      <div class="input-append"><input class="span1" style="max-width:34px" placeholder="1" id="appendedInputButtons" size="16" type="text"> 
       <button class="btn" type="button"><i class="icon-minus"></i></button> 
       <button class="btn" type="button"><i class="icon-plus"></i></button> 
       <button class="btn btn-danger" type="button" onclick="removeItem(item.id)"><i class="icon-remove icon-white"></i></button> 
      </div> 
     </td> 
     <td>$120.00</td> 
     <td>$25.00</td> 
     <td>$15.00</td> 
     <td>$110.00</td> 
    </tr> 
{% endfor %} 

UPDATE這是我已經做了:在控制器

removeAction:

public function removeAction($itemId) 
{ 
    $session = $this->getRequest()->getSession(); 
    $session->remove(); 
    return $this->render('MpShopBundle:Frontend:product_summary.html.twig');  
} 

控制器路由:

removeItem: 
    pattern: /remove 
    defaults: { _controller: MpShopBundle:Homepage:remove } 

腳本:

<script> 

    $(".btn btn-danger").click(function(){ 
     var itemId = $(this).val(); 
     $.ajax({ 
      type: "POST", 
      url: "{{ path('removeItem') }}", 
      data: { itemId: itemId } 
     }); 

</script> 

按下按鈕沒有做任何事情,即時通訊並不感到驚訝,因爲這是我第一次真正使用javascript我想我做錯了什麼?

回答

2

是的,你可以在Ajax!

  1. 在控制器中創建您的操作,該控制器刪除會話的給定產品。

一個示例代碼:

ProductController extends Controller{ 
    ... 

    public function removeItemAction($itemId){ 

     //find here your session where you save the item. 

     //and remove it 

     //return a response depending on what you want in the format that you want (json,xml,...) 
     return new Response("..."); 
    } 
} 

2.創建你的JavaScript代碼,聽的動作,併發送請求阿賈克斯的先例網址。 (如果您使用jQuery,請參閱$ .ajax)

  1. 更新您的DOM(刪除正確的元素或加載任何您需要的html)。
+0

因爲我是相當新的節目,你可以解釋一下第一部分更從JavaScript調用它簡單? – Dominykas55

+0

更清楚嗎? – MouradK

+0

好的。變量$ itemId必須在javascript函數中指定,然後根據id刪除會話。答覆部分對我來說並不清楚。它和渲染一樣嗎? – Dominykas55

0

只使用JavaScript,您可以不。 您的PHP會話只能通過php訪問。你能做的唯一的事情就是創建一個PHP函數,消除任何你想要從會話,並使用AJAX調用像@MouradK說

相關問題