2015-02-08 121 views
2

我試圖用PHP開發一個簡單的任務列表。我有一個使用樹枝http://twig.sensiolabs.org/每個循環的任務列表。如果任務被標記爲完成,則檢查該複選框。我的問題是,如何將每個複選框附加到一個腳本,以便使用不同的參數進行ajax調用,以便服務器知道正在檢查哪個任務?XMLHttpRequest/AJAX請求在一個樹枝中發送循環

<table> 
    <thead> 
     <tr> 
      <th>Task</th> 
      <th>Valmis</th> 
     </tr> 
    </thead> 
    <tbody> 
     {% for task in tasks %} 
     <tr> 
      <td>{{task.description}}</td> 
      <td><input type="checkbox" {{ task.done ? "checked" : "" }} ></td> 
     </tr> 
     {% endfor %} 
    </tbody> 
</table> 
+0

你可以給每個任務添加一個id,並讓它連接到輸入。這樣你就會知道哪個任務被點擊了。 – Abhishek 2015-02-08 11:45:19

+0

Hi @MikkoÖversti您是否找到解決方案? – Matteo 2015-02-10 15:20:22

+0

謝謝Abhishek和@Matteo – 2015-02-13 08:42:14

回答

2

我添加了一個類實現的形式Ajax調用,並通過POST到服務器,使其和管理響應,像這樣的例子:

Javascript代碼:

$(document).ready(function() { 
      $('.lista-proroghe-item').each(function(){ 
       $(this).find('.perform-ajax-request-button').click(function(){ 
        var form = $(this).closest("form"), action = form.attr('action'); 
        var currentButton = $(this); 
        var currentMessage = $(this).next('.proroga-messaggio'); 

        $(this).attr('disabled', 'disabled'); 
        $(this).html('Processing...'); 

        $.ajax({ 
         url: action, 
         type: "POST", 
         data: form.serialize(), 
         success: function(data) { 
          // console.log(data); 
          $(currentButton).hide(); 
          $(currentMessage).html('<span>'+data.description+'<br>'+data.extendedMessage+'</span>'); 
         } 
        }); 
        e.preventDefault(); 
        return false; 
       }) 
      }) 
     }); 

嫩枝代碼:

{% for extension in assignation.contract.contractModificationDurations %} 
    <li class="lista-proroghe-item"> 
     <form action="{{ path('contractExtension', {'idContractModification' : extension.idContractModification, 'userid':user.id }) }}"> 
      Element 
      <button class="button small perform-ajax-request-button right"><span class="refresh">to task</span></button> 
      <div class="proroga-messaggio"></div> 
     </form> 
    </li>   
{% else %} 
    <li> 
     Nessuna proroga trovata 
    </li> 
{% endfor %} 

希望得到這個幫助。