2014-06-09 5 views
0

SPServices를 사용하여 SharePoint에서 채워진 두 개의 드롭 다운이 있습니다. 이 부분은 훌륭하게 작동합니다. 그런 다음, 클릭하면 SharePoint에서 데이터를로드하고 필터로 드롭 다운 텍스트를 사용하여 DataTables 플러그인을 사용하여 테이블을 채울 데이터를 가져 오는 버튼이 있습니다. 이 부분은 한 번만 작동합니다. 버튼을 다시 클릭하면 아무 일도 일어나지 않습니다.이벤트는 jQuery에서 Ajax 요청을 수행 할 때 한 번만 발생합니다.

 function run() { 

theYear = $('#dropdown option:selected').text(); // Selected Year 
theRO = $('#dropdownRO option:selected').text(); // Selected RO 
var call = $.ajax({ 
    url: "https://blah-blah-blah/_api/web/lists/getByTitle('Consolidated%20LC%20Report')/items()?$filter=Fiscal_x0020_Year%20eq%20'" + theYear + "' and Regional_x0020_Office eq '" + theRO + "'&$orderby=Id&$select=Id,Title,Fiscal_x0020_Year,Notices_x0020_Received,Declined_x0020_Participation,Selected_x0020_Field_x0020_Revie,Selected_x0020_File_x0020_Review,Pending,Pending_x0020_Previous_x0020_Yea,Controversial,GFP_x0020_Reviews,NAD_x0020_Appeals,Mediation_x0020_Cases,Monthly_x0020_Cost_x0020_Savings,Monthly_x0020_Expenditure,Regional_x0020_Office,Month_Number", //Works, filters added 
    type: "GET", 
    cache: false, 
    dataType: "json", 
    headers: { 
     Accept: "application/json;odata=verbose", 
    } 
}); //End of ajax function/// 
call.done(function (data, textStatus, jqXHR) { 
    var oTable = $('#example').dataTable({ 
     "aLengthMenu": [ 
      [25, 50, 100, 200, -1], 
      [25, 50, 100, 200, "All"] 
     ], 
      "iDisplayLength": -1, //Number of rows by default. -1 means All Records 
     "sPaginationType": "full_numbers", 
      "aaData": data.d.results, 
      "bJQueryUI": false, 
      "bProcessing": true, 
      "aoColumns": [{ 
      "mData": "Id", 
      "bVisible": false 
     }, //Invisible column 
     { 
      "mData": "Title" 
     }, { 
      "mData": "Notices_x0020_Received" 
     }, { 
      "mData": "Declined_x0020_Participation" 
     }, { 
      "mData": "Selected_x0020_Field_x0020_Revie" 
     }, { 
      "mData": "Selected_x0020_File_x0020_Review" 
     }, { 
      "mData": "Pending" 
     }, { 
      "mData": "Pending_x0020_Previous_x0020_Yea" 
     }, { 
      "mData": "Controversial" 
     }, { 
      "mData": "GFP_x0020_Reviews" 
     }, { 
      "mData": "NAD_x0020_Appeals" 
     }, { 
      "mData": "Mediation_x0020_Cases" 
     }, { 
      "mData": "Monthly_x0020_Cost_x0020_Savings", 
      "fnRender": function (obj, val) { 
       return accounting.formatMoney(val); 
      } 
     }, { 
      "mData": "Monthly_x0020_Expenditure", 
      "fnRender": function (obj, val) { 
       return accounting.formatMoney(val); 
      } 
     }], 
      "bDeferRender": true, 
     "bRetrieve": true, 
     "bInfo": true, 
     "bAutoWidth": true, 
     "bDestroy": true, 
      "sDom": 'T&;"clear"&;frtip', 
      "oTableTools": { 
      "aButtons": ["xls"], 
       "sSwfPath": "../../Style Library/js/datatables/TableTools/media/swf/copy_csv_xls_pdf.swf", 
     }, 
      "sSearch": "Filter", 
      "fnDrawCallback": function() { 
      //Add totals row 
      var Columns = $("#example > tbody").find("> tr:first > td").length; 
      $('#example tr:last').after('<tr><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td></tr>'); 
      //Formating the Total row number to no decimals 
      $("#example tr:last td:not(:first,:last)").text(function (i) { 
       var t = 0; 
       $(this).parent().prevAll().find("td:nth-child(" + (i + 2) + ")").each(function() { 
        t += parseFloat($(this).text().replace(/[\$,]/g, '') * 1); 
       }); 
       return parseInt(t * 100, 10)/100; 
      }); 
      //Format the monthly expenditure and savings to currency formatFormating the currency 
      var cell = new Array(); 
      cell[0] = $('#example tr:last td:nth-child(12)').text(); 
      cell[1] = $('#example tr:last td:nth-child(13)').text(); 
      $('#example tr:last').find('td:nth-child(12)').html(accounting.formatMoney(cell[0])); 
      $('#example tr:last').find('td:nth-child(13)').html(accounting.formatMoney(cell[1])); 
      $('#example tr:last').find('td:last').hide(); 
     } //hides extra td that was showing 
    }); //End of Datatable() 
}); //End of call.done function 
$('#theTableDiv').slideDown(); 
} //end of run() function 

:

$(document).ready(function() { 
var theYear; // Selected Year 
var theRO; // Selected RO 
//Fills the Dropdown lists (Year and RO) 
$().SPServices({ 
    operation: "GetListItems", 
    async: false, 
    listName: "{ListID}", 
    CAMLViewFields: "<ViewFields><FieldRef Name='Fiscal_x0020_Year' /><FieldRef Name='Regional_x0020_Office' /></ViewFields>", 
    completefunc: function (xData, Status) { 
     //Add Select Value option 
     $("#dropdown").prepend($('<option>', { 
      value: '', 
      text: 'Select Fiscal Year' 
     })); 
     $("#dropdownRO").prepend($('<option>', { 
      value: '', 
      text: 'Select Regional Office' 
     })); 
     //Fetching Data from SharePoint  
     $(xData.responseXML).SPFilterNode("z:row").each(function() { 
      var dropDown = "<option value='" + $(this).attr("ows_Fiscal_x0020_Year") + "'>" + $(this).attr("ows_Fiscal_x0020_Year") + "</option>"; 
      var dropDownRO = "<option value='" + $(this).attr("ows_Regional_x0020_Office") + "'>" + $(this).attr("ows_Regional_x0020_Office") + "</option>"; 
      $("#dropdown").append(dropDown); 
      $("#dropdownRO").append(dropDownRO); 
      /////////////Deletes duplicates from dropdown list//////////////// 
      var usedNames = {}; 
      $("#dropdown > option, #dropdownRO > option").each(function() { 
       if (usedNames[this.text]) { 
        $(this).remove(); 
       } else { 
        usedNames[this.text] = this.value; 
       } 
      }); 
      ////Deletes repeated rows from table 
      var seen = {}; 
      $('#myTable tr, #tasksUL li, .dropdown-menu li').each(function() { 
       var txt = $(this).text(); 
       if (seen[txt]) $(this).remove(); 
       else seen[txt] = true; 
      }); 
     }); 
    } //end of completeFunc 
}); //end of SPServices 
$('.myButton').on('click', function() { 
    run() 
}); 
}); //End jQuery Function 

이 내가 내가 드롭 다운에서 내 선택을 변경 한 후 "을 myButton"클릭 할 때마다 실행하는 데 필요한 기능은 다음과 같습니다

이 내가 드롭 다운을 채우는 방법입니다 나는 프로그래머가 아니에요, 나는 단지 배우려고 노력하고 있습니다. 나는 어떤 도움을 주셔서 감사합니다. 미리 감사드립니다.

+1

브라우저 콘솔에 오류가 있습니까? 버튼 클릭 사이에 페이지 새로 고침이 없다고 가정하면 이미 초기화 된 요소 (#example)에 대해 DataTables를 초기화하려고 할 가능성이 큽니다. 이 경우 콘솔에 오류가 있음을 확인하는 메시지가 표시됩니다. DataTables가 이미 초기화 된 경우 적절한 접근 방법은 API를 사용하여 기존 테이블을 업데이트 한 다음 .draw()를 통해 새로 고치는 것입니다. http://datatables.net/reference/api/draw%28%29 – Stevangelista

+0

Thanks Stevangelista! 나는 전혀 오류가 발생하지 않습니다. 나는 네가 옳다고 생각하는데, 두통을 안겨주는 DataTables 인 것 같다. 내가 draw(), drawCallback(), 등, 등, 그리고 행운을 시도했다. 나는 내가 생각한 것을 성취하기 위해 너무 가까워지고 있었다. – cubanGuy

+0

왜 jQuery AJAX를 사용하고 있습니까? [자체 AJAX 기능을 가지고 있습니다] (http://datatables.net/examples/data_sources/ajax.html) 재 초기화 할 필요가 없습니다. – mason

답변

1

버튼이있는 페이지 부분을 대체한다고 생각합니다. (JSFiddle.net과 TidyUp 버튼을 사용하여 코드를 좀 더 깔끔하게 포맷해야한다).

그건 당신이 위임 이벤트 핸들러 사용해야하는 경우라면 : 이벤트가 발생할 때

$(document).on('click', '.myButton', function() { 
    run() 
}); 

이 원하는 노드의 정적 조상에서 수신, 다음, 선택기를 실행은은 이벤트를 유발 한 일치하는 요소에 함수를 적용합니다.

document은 편리한 조상이없는 경우 대체 부모입니다. 이상한 행동을하기 때문에 위임 된 이벤트에 '본문'을 사용하지 마십시오.

+0

코드 제안 및 TidyUp 도구 (매우 유용합니다)에 감사드립니다. 그러나 당신의 해결책은 효과가 없습니다. Stevangelista가 제안한 것처럼 문제는 DataTables 플러그인입니다. 어떻게 든 내 버튼에 draw() 또는 drawCallback() 함수를 바인딩해야하며, 지금까지 행운을 얻지 못했습니다. – cubanGuy

+0

수치심. 그 중 90 %는 * 한 번만 작동합니다 * 문제 : 포맷 된대로 코드를 읽는 것이 어렵 기 때문에 TidyUp을 적용하십시오. –