2017-11-10 1 views
1

프로젝트에서 ASP.NET MVC 5, jquery 및 datatables 플러그인으로 작업하고 있습니다. 필자의 목표는 데이터베이스의 데이터를 검색 한 다음 데이터 테이블에 dat을 표시하기 위해 datatables의 서버 측 기능을 사용하는 것입니다. 이것은 내 코드의 한 부분에서 잘 작동합니다. 여기에 내가 datatables 플러그인을 사용하는 jQuery 코드 볼 수 있습니다datatables 플러그인 내의 AJAX 요청은 코드의 모든 부분에서 작동하지 않습니다.

var problemTable = $('#ProblemTable').DataTable({ 
    processing: true, // show message while querying fro data 
    serverSide: true, 
    ajax: { 
     url: "/OverView/LoadProblems" 
    } 
}); 

다음 그림에서 볼 수 있듯이을, 요청이 성공적으로 내 datatables은 (는) 웹 사이트에서와 예상대로 채워집니다.

Success

요청 URL은 다음과 같습니다

Success_Url

것은 지금까지 모두 괜찮습니다. 하지만 지금은 나를 미치게하는 부분이 있습니다. 다른 jquery 스크립트에서 나는 새로운 datatable에 대한 datatables 메소드를 다시 호출하려고합니다. 코드는 다음과 같습니다.

$('.DeleteEntity').click(
function() { 
    try 
    { 
     var deleteTable = $('#DeleteTable').DataTable({ 
      processing: true, 
      serverside: true, 
      destroy: true, 
      ajax: { 
       url: "/Administration/ShowEntriesDelete" 
      } 
     }); 
    } 
    catch (e) 
    { 
     console.log(e); 
    } 
}); 

이 Ajax 호출은 더 이상 작동하지 않습니다. 다음 그림을 볼 수 있듯이 C# 코드의 작업 메서드가 실패합니다. 이 경우

Error

는 요청 URL은 다음과 같습니다. 그래서 여기

Error_Url

내 질문입니다 : 내 jQuery 코드에서 동일한 기능을 사용할 수 있지만, 왜 내가이 동작을받을 수 있나요? 아니면 내가 완전히 잘못한 것이 있습니까?

나는 지금까지 모든 것을 시도했지만 아직 이해가 안된다고 생각합니다. 두 데이터 테이블은 HTML에서 완전히 동일하게 보이지만 ID와 열 머리글 만 다릅니다.

나는 비슷한 질문을했지만, 아무것도 찾을 수 없었다. 누군가가 나에게이 점에 대한 힌트를 줄 수 있다면 정말 기뻐할 것입니다.

감사합니다.

는 편집 : @Calvin 아난다

나는 당신의 대답을 적응 단지 테스트 목적을 위해, 하나의 스크립트에 DataTable의 기능을 모두 추가했다. 다음은 구멍 스크립트입니다.

var troubleshootingIDs = []; 
$(document).ready(
    function() { 

    // if I call this method, everything works just fine, the c# code throws an error (which it should) but the ajax method is successfull 
    var problemTable = $('#ProblemTable').DataTable({ 
     processing: true, // show message while querying fro data 
     serverSide: true, 
     "ajax": "/Administration/ShowEntriesDelete" 
    }); 

    // if I call this method, the ajax method doesnt get called, because there is absolute no data provided in the url 
    var deleteTable = $('#DeleteTable').DataTable({ 
     processing: true, 
     serverside: true, 
     destroy: true, 
     "ajax": "/Administration/ShowEntriesDelete", 
     "columns": [ 
      { "data": "Description" }, 
      { "data": "Connection" }, 
      { "data": "Action" } 
     ] 

    }); 


    var table = $('#reasonTable').DataTable({ 
     pageLength: 2, 
     lengthChange: false, 
     columnDefs: [ 
      { 
       targets: [3], 
       className: "hide_me" 
      } 
     ] 
    } 
    ); 

    var agentButton = $('.agentButton'); 


    $('td').on('click', '#BadgeContainer', function() { 
     var IDs = []; 
     $('#DocList').empty(); 
     $('.DocLinkID').each(function (counter) { 
      IDs[counter] = $(this).html(); 
     }); 
     console.log(IDs); 

     $.ajax({ 
      url: "/OverView/GetDocuments", 
      traditional: true, 
      data: { IDs: IDs }, 
      content: 'application/json; charset=utf-8', 
      success: listDocuments 
     }); 
    }); 



    $('#reasonTable tbody').on('click', 'tr', function() { 

     $('#SolutionList').empty(); 
     troubleshootingIDs = []; 

     if ($(this).hasClass('selected')) { 

     } 
     else { 
      table.$('tr.selected').removeClass('selected'); 
      $(this).addClass('selected'); 
     } 

     var selectedReason = $('.ReasonGuid', this).text(); 


     $.ajax({ 
      url: '/OverView/ReasonJson', 
      contentType: 'application/json; charset=utf-8', 
      data: { 'selectedReason': selectedReason }, 
      success: handleJsonForWizard 
     } 
     ); 

    } 
    ); 

    $('.SolutionButton').on('click', 
     function() { 

      var indexToRemove = []; 
      var dummyArray = []; 

      for (var counter = 0; counter < troubleshootingIDs.length; counter++) { 
       if ($('#q' + (+counter * 2)).hasClass('btn-active')) { 
        indexToRemove.push(counter); 
       } 

       dummyArray[counter] = troubleshootingIDs[counter]; 
      } 


      for (var counter = indexToRemove.length - 1; counter >= 0; counter--) { 
       dummyArray.splice(indexToRemove[counter], 1); 
      } 

      $.ajax(
       { 
        url: '/OverView/GetSolutions', 
        contentType: 'application/json; charset=utf-8', 
        traditional: true, 
        data: { troubleshootingIDs: dummyArray }, 
        success: function (json) { 
         $('#SolutionList').empty(); 

         try { 
          for (var counter = 0; counter < Object.keys(json).length; counter++) { 
           $('#SolutionList').append('<li class="list-group-item">' + json[counter] + '</li>'); 
          } 
         } 

         catch (err) { 

         } 
        } 
       } 
      ); 
     } 
    ); 

    $('#ProblemTable tbody').on('click', '.WizardButton', 
     function() { 
      var IdToGet = $(this).attr('id'); 

      var url = '/OverView/Wizard?SelectedID='; 

      window.location.replace(url + IdToGet); 

     } 

    ); 

    // Carousel fuction overriding (doesn't work wiht jquery template) 

    $('.carousel-control.left').click(
     function() { 

      var parentId = '#' + $(this).parent().attr('id'); 

      $(parentId).carousel('prev'); 
     } 
    ); 

    $('.carousel-control.right').click(
     function() { 

      var parentId = '#' + $(this).parent().attr('id'); 

      $(parentId).carousel('next'); 
     } 
    ); 


    // comment to define 

    $('.row #BackToTable').click(
     function() { 
      window.location.replace("/OverView"); 
     } 

    ); 



    $('body').on('click', '.AgentButton', 
     function() { 


      var idNum = $(this).attr('id'); 

      var num = idNum.substring(1); 

      $('#' + idNum).toggleClass('btn-active'); 

      if ((num % 2) == 0) { 

       var numToCompare = +num + 1; 
       var classToCompare = $('#q' + numToCompare).attr('class'); 

       if (classToCompare == 'btn AgentButton btn-active') { 
        $('#q' + numToCompare).toggleClass('btn-active'); 
       } 
      } 


      else { 

       var numToCompare = +num - 1; 
       var classToCompare = $('#q' + numToCompare).attr('class'); 

       if (classToCompare == 'btn AgentButton btn-active') { 
        $('#q' + numToCompare).toggleClass('btn-active'); 
       } 
      } 

     } 
    ); 


    function handleJsonForWizard(json) { 

     initializeCarousel(json.ImgLinks); 
     initializeAgent(json.Troubleshootings, json.TroubleshootingIDs); 
    } 


    function initializeCarousel(imgLinks) { 

     $('#ReasonVisualisation > ol').empty(); 
     $('#ReasonVisualisation > .carousel-inner').empty(); 
     for (var counter = 0; counter < Object.keys(imgLinks).length; counter++) { 
      $('#ReasonVisualisation > ol').append('<li data-target="#ReasonVisualisation" data-slide-to="' + counter + '"></li>'); 
      $('#ReasonVisualisation > .carousel-inner').append('<div class="item"><img src="' + imgLinks[counter] + '"/> </div>'); 
     } 

     $('#ReasonVisualisation > ol >li:first').addClass('active'); 
     $('#ReasonVisualisation > .carousel-inner>div:first').addClass('active'); 

     var list = $('#ReasonVisualisation > ol').html(); 

     var inner = $('#ReasonVisualisation > .carousel-inner').html(); 


    } 

    function initializeAgent(troubleshootings, ids) { 
     $('#Agent').empty(); 
     for (var counter = 0; counter < Object.keys(troubleshootings).length; counter++) { 
      $('#Agent').append('<div>' + troubleshootings[counter] + ' </div>'); 
      $('#Agent').append('<div class="btn AgentButton" id="q' + (counter * 2) + '">Yes</div>'); 
      $('#Agent').append('<div class="btn AgentButton" id="q' + ((counter * 2) + 1) + '">No</div>'); 
      agentButton = $('.AgentButton'); 
      troubleshootingIDs[counter] = ids[counter]; 
     } 
    } 


    function listDocuments(json) { 
     //Array.isArray(json); 
     if (json.length > 1) { 
      for (var counter = 0; counter < json.length; counter++) { 
       $('#DocList').append('<li> <a href=\"' + json[counter] + '\" > Link </a></li>'); 
      } 
     } 
    } 
} 

);

가장 흥미로운 부분은 스크립트의 첫 번째 메소드입니다. 코드 내 제공된 코드에서 내 문제를 설명했습니다. 나는 왜 아약스가 다른 반응을 보이는지 간단히 알지 못한다 ...

답변

0

나는이 방법을 내 프로젝트에서 사용하고있다.

그러나 문제가 해결되는지 잘 모르겠다.

JSFiddle Here

변경 "ajax": "/OverView/LoadProblems"

var problemTable = $("#ProblemTable").DataTable({ 
    processing: true, // show message while querying fro data 
    serverSide: true, 
    "ajax": "/OverView/LoadProblems" 
}); 

=============================== ==========================

$(".DeleteEntity").click(
function() { 
    try 
    { 
     var deleteTable = $("#DeleteTable").DataTable({ 
      processing: true, 
      serverside: true, 
      destroy: true, 
      "ajax": "/Administration/ShowEntriesDelete" 
     }); 
    } 
    catch (e) 
    { 
     console.log(e); 
    } 
}); 
+0

감사합니다. 귀하의 노력으로 인해, 귀하의 제공된 수정이 제 솔루션에서 작동하지 않았습니다. –

+0

$ (문서) .ready (함수() {})를 추가 할 수 있습니까? 당신의 대본에? – Ananda

+0

나는 내 게시물을 편집 했으므로 스크립트를 볼 수 있습니다. 고마워,) –

관련 문제