2012-04-04 1 views
1

내 문제는 다음과 같습니다. 일부 레코드와 관련된 데이터를 가져와 폼에서 사용할 수있게 만듭니다.상호 관련 드롭 다운 목록이있는 편집 할 양식로드

중요한 것은 3 개의 상호 관련 드롭 다운 목록으로 표시되는 위치 (대륙, 국가, 도시)입니다.

내가 얻는 것은 브라우저가 응답을 멈추는 것이므로, 더 좋은 해결책을 내놓기 위해 몇 가지 아이디어가 필요합니다.

// To load the drop-down lists I use similar ajax code as the one shown below in the edit case 

function processRow(command, id) { 
    switch(command){ 

    case 'Delete': {  
     $("#deleteId").val(id); 
     $('#deleteEventModal').reveal(); 
    } 
    break; 
    case 'Edit': { 
     /* Fetch Data to Fill up the form */ 
     $.ajax({ 
      type: "GET", 
      url: "scripts/fetchEventById.php?eventId=" + encodeURIComponent(id), 
      dataType: "json", 
      success: function(response){ 
        /* On Successful Posting to server side */ 
           // THIS DROP DOWN LOADS AND SETS DB VAL OK 
        loadContinents("#editEventContinents"); 
        $("#editEventContinents").val(response.eventData.continentId);   

        // FROM THIS MOMENT ON IT WILL STALL 
        // last instruction sets continent drop-down with proper value BUT 
        // when fetching the countries for that continent (below) 
        // the continent drop-down value comes empty as if nothing 
        // was selected 
        // but it was, I visually confirmed that 
        // after setting it with val() above 
        loadCountries("#editEventContinents", "#editEventCountries", "#editEventCities"); 
        $("#editEventCountries").val(response.eventData.countryId); 

        loadCities("#editEventCountries", "#editEventCities"); 
        $("#editEventCities").val(response.eventData.cityId); 

        $("#editEventStartDate").val(response.eventData.startDate); 
        $("#editEventEndDate").val(response.eventData.endDate); 
        $("#editEventUserName").val(response.eventData.userName); 
        $("#editEventName").val(response.eventData.eventName); 
        $("#editEventDetails").val(response.eventData.details); 
      }, 
      error: function(jqXHR, textStatus, errorThrown){    
       /* log the error to the console */ 
       console.log(
        "The following error occured: " + 
        textStatus, errorThrown 
       ); 
      } 
     }); 

     // Get the overlay with the form for editing to pop up        
     $('#editEventModal').reveal(); 
    } 
    break; 
    default: 
     // oops, something wrong happened 
    break; 
} 
return false; 
} 

// Here is the load continents function 
function loadContinents(continentObj) {  
// fetch continent data 

$.ajax({ 
    type: "GET", 
    url: "scripts/fetchContinents.php", 
    dataType: "json", 
    success: function(data){ 
     /* On Successful Posting to server side */ 

     // Add fetched options to the select object responsible for holding the continents list 
     $(continentObj).empty(); //clear current available selections 
     if(data == ""){ 
      $(continentObj).append("<option value=\"\">No continents found</option>"); 
     } 
     else{ 
      for(i = 0; i < data.id.length; i++){ 
       $(continentObj).append("<option value=\"" + data.id[i] + "\">" + data.name[i] + "</option>"); 
      } 
     } 

    }, 
    error: function(jqXHR, textStatus, errorThrown){ 
     /* log the error to the console */ 
     console.log(
      "The following error occured: " + 
      textStatus, errorThrown 
     ); 

     $(countryObj).append("<option selected value=\"\">Select Continent</option>"); 

     $("#searchEventError").fadeOut(200); 
     $("#searchEventError").fadeIn(200).html("<div class=\"alert-box error\">Something went wrong with the server request, please try again later</div>"); 
    } 
}); 

return false; 
} 

// Load Countries 
function loadCountries(continentObj, countryObj, cityObj) { 
var continentOption = $(continentObj).val(); 

// clear/reset countries and cities selections 
$(countryObj).empty(); 
$(cityObj).empty().append("<option selected value=\"-1\">Please Select Country First</option>"); 

$.ajax({ 
    type: "GET", 
    url: "scripts/fetchCountries.php?continent=" + encodeURIComponent(continentOption), 
    dataType: "json", 
    success: function(data){ 
     /* On Successful Posting to server side */ 

     // Add fetched options to the select object responsible for holding the countries list 
     if(data == ""){ 
      $(countryObj).append("<option value=\"0\">No countries found</option>"); 
     } 
     else{ 
      for(i = 0; i < data.id.length; i++){ 
       $(countryObj).append("<option value=\"" + data.id[i] + "\">" + data.name[i] + "</option>"); 
      } 
     } 

    }, 
    error: function(jqXHR, textStatus, errorThrown){ 
     /* log the error to the console */ 
     console.log(
      "The following error occured: " + 
      textStatus, errorThrown 
     ); 

     $(countryObj).append("<option selected value=\"-1\">Please Select Continent First</option>"); 

     $("#searchEventError").fadeOut(200); 
     $("#searchEventError").fadeIn(200).html("<div class=\"alert-box error\">Something went wrong with the server request, please try again later</div>"); 

    } 
}); 

return false; 
} 

// Load Cities 
function loadCities(countryObj, cityObj) { 
var countryOption = $(countryObj).val(); 

// clear/reset cities selections 
$(cityObj).empty(); 

$.ajax({ 
    type: "GET", 
    url: "scripts/fetchCities.php?country=" + encodeURIComponent(countryOption), 
    dataType: "json", 
    success: function(data){ 
     /* On Successful Posting to server side */ 

     // Add fetched options to the select object responsible for holding the cities list  
     if(data == ""){ 
      $(cityObj).append("<option value=\"0\">No cities found</option>"); 
     } 
     else{ 
      for(i = 0; i < data.id.length; i++){ 
       $(cityObj).append("<option value=\"" + data.id[i] + "\">" + data.name[i] + "</option>"); 
      } 
     } 

    }, 
    error: function(jqXHR, textStatus, errorThrown){    
     /* log the error to the console */ 
     console.log(
      "The following error occured: " + 
      textStatus, errorThrown 
     ); 

     $(cityObj).append("<option selected value=\"-1\">Please Select Country First</option>"); 

     $("#searchEventError").fadeOut(200); 
     $("#searchEventError").fadeIn(200).html("<div class=\"alert-box error\">Something went wrong with the server request, please try again later</div>"); 
    } 
}); 

return false; 
} 
+0

브라우저가 응답을 중지한다고 말하면 완전히 잠긴 것입니까? 검색 주소창에 입력 할 수없고 다른 사이트로 이동할 수 있습니까? 아니면 Javascript가 처리를 중지한다는 의미입니까? – AlexC

+0

브라우저가 잠겨있는 것처럼 보입니다. 질문은 다음과 같습니다. 왜 $ ("# editEventContinents")가 아닌지 val (continentId); 해당 대륙의 국가를 가져올 수 있도록 대륙 옵션에서 선택된 값으로 지정 하시겠습니까? fetch countries querystring에서 대륙 매개 변수가 비어있는 경우가 있습니다. 결과적으로 도시에서도 마찬가지입니다. –

+0

전체 코드를 보는 것이 도움이됩니다. loadContinents가 무엇을하고 있는지 알지 못하는 것을 제외하면 브라우저에 치명적인 문제가되지 않습니다. 전체 코드를 게시하십시오. 제가 살펴 보겠습니다. – AlexC

답변

1

귀하의 loadCountriesprocessRow의 내부에 포함되어 있으므로 이벤트 값이 돌아오고되고있다 : 여기

는, 그래서 아마 누군가가 나에게 힌트를 줄 수있는 포장 마차 위치에 주석이있는 코드의 샘플입니다 설정하지만 loadCountries가 들어 와서 해당 값을 다시 덮어 씁니다.

inital로드에서 선택한 값을 기반으로 국가 및 도시 데이터를 가져 와서 여러 번 기다릴 필요가 없습니다. 선택한 대륙의 모든 국가, 선택한 국가의 모든 도시 및 이벤트 세부 정보 JSON을 포함하도록 이벤트 세부 정보를 가져옵니다.

각 하나 (내가 이것을하지 않는 것이 좋습니다)과 같이 다음을 기다릴 필요가 있도록 AJAX 호출을 중첩됩니다 시도 할 수 있습니다 다른 것은 : 내가 의미하는 것은

function processRow(command, id) { 
    console.log('Starting the processing of row #' +id); 
    switch(command){ 

     case 'Delete': {  
      $("#deleteId").val(id); 
      $('#deleteEventModal').dialog("open"); 
     } 
     break; 
     case 'Edit': { 
      /* Fetch Data to Fill up the form */  

      $.ajax({ 
       type: "GET", 
       url: "stackAjax.php?Action=Event&eventId=" + encodeURIComponent(id), 
       dataType: "json", 
       success: function(response){ 
        $("#editEventStartDate").val(response.eventData.startDate); 
        $("#editEventEndDate").val(response.eventData.endDate); 
        $("#editEventUserName").val(response.eventData.userName); 
        $("#editEventName").val(response.eventData.eventName); 
        $("#editEventDetails").val(response.eventData.details); 
        $("#editEventContinents").val(response.eventData.continentId); 

        /* On Successful Posting to server side */ 
        window.currentContinent = response.eventData.continentId; 
        window.currentCountry = response.eventData.countryId; 
        window.currentCity = response.eventData.cityId; 

        var countryObj = $("#editEventCountries"), 
        cityObj = $("#editEventCities"); 

        $(countryObj).empty(); 
        $(cityObj).empty().append("<option selected value=\"-1\">Please Select Country First</option>"); 

        $.ajax({ 
         type: "GET", 
         url: "stackAjax.php?Action=Countries&continent=" + encodeURIComponent(window.currentContinent), 
         dataType: "json", 
         success: function(countryData){ 
          /* On Successful Posting to server side */ 

          // Add fetched options to the select object responsible for holding the countries list 
          if(countryData == ""){ 
           $(countryObj).append("<option value=\"0\">No countries found</option>"); 
          } 
          else{ 
           for(i = 0; i < countryData.id.length; i++){ 
            $(countryObj).append("<option value=\"" + countryData.id[i] + "\">" + countryData.name[i] + "</option>"); 
           } 
          } 

          $(cityObj).empty(); 

          console.log('about to set the country');   
          $("#editEventCountries").val(response.eventData.countryId); 
          $.ajax({ 
           type: "GET", 
           url: "stackAjax.php?Action=Cities&country=" + encodeURIComponent(window.currentCountry), 
           dataType: "json", 
           success: function(cityData){ 
            /* On Successful Posting to server side */ 

            // Add fetched options to the select object responsible for holding the cities list  
            if(cityData == ""){ 
             $(cityObj).append("<option value=\"0\">No cities found</option>"); 
            } 
            else{ 
             for(i = 0; i < cityData.id.length; i++){ 
              $(cityObj).append("<option value=\"" + cityData.id[i] + "\">" + cityData.name[i] + "</option>"); 
             } 
            } 

           console.log('about to set the city');  
           $("#editEventCities").val(response.eventData.cityId); 
           }, 
           error: function(jqXHR, textStatus, errorThrown){    
            /* log the error to the console */ 
            console.log(
             "The following error occured: " + 
             textStatus, errorThrown 
            ); 

            $(cityObj).append("<option selected value=\"-1\">Please Select Country First</option>"); 

            $("#searchEventError").fadeOut(200); 
            $("#searchEventError").fadeIn(200).html("<div class=\"alert-box error\">Something went wrong with the server request, please try again later</div>"); 
           } 
          }); 
         }, 
         error: function(jqXHR, textStatus, errorThrown){ 
          /* log the error to the console */ 
          console.log(
           "The following error occured: " + 
           textStatus, errorThrown 
          ); 

          $(countryObj).append("<option selected value=\"-1\">Please Select Continent First</option>"); 

          $("#searchEventError").fadeOut(200); 
          $("#searchEventError").fadeIn(200).html("<div class=\"alert-box error\">Something went wrong with the server request, please try again later</div>"); 

         } 
        }); 

        //console.log('A: Country DB: ' + response.eventData.countryId); 
        //$("#editEventCountries").change(); 

        //console.log('A: Selected Country: ' + $("#editEventCountries").val()); 


        //console.log('A: Selected City: ' + $("#editEventCities").val()); 

        //$('#editEventModal').dialog("open"); 
       }, 
       error: function(jqXHR, textStatus, errorThrown){    
        /* log the error to the console */ 
        console.log(
         "The following error occured: " + 
         textStatus, errorThrown 
        ); 
       }, 
       complete: function(){ 

       } 
      }); 
     } 
     break; 
     default: 
      alert("Don't know what to do but id is "+id); 
     break; 
    } 
    return false; 
} 
+0

좋습니다. 감사합니다. 나중에 결과를 게시하겠습니다 :) –

+0

흠 ... 더 자세히 조사했습니다. 나는 네가 틀린 장소를보고 있다고 생각한다. 이 동적 상자는 다른 것들을 위해 작동합니다. 문제는 다음과 같습니다. 표에서 한 줄을 클릭하고 편집을 누릅니다. 기록을 갱신하고 싶습니다. 그리고 기록에는 대륙, 국가 및 도시에 기반을 둔 위치가 있습니다. 따라서 편집 양식에도 이러한 동적 드롭 다운이 있습니다. 문제는 다음과 같습니다. DB에서 오는 해당 레코드의 대륙은 정상적으로 작동합니다. val() 메서드를 사용하여 내가 가진 레코드를 사용하여 폼의 드롭 다운을 설정합니다. 하지만 국가 데이터를 가져 오지 못합니다. 등등. –

+0

내 말은 : 당신이 쓴 것과 내가 썼던 것의 유일한 실용적인 차이점은 하나의 상자에서 다른 상자로의 변화를 촉구하는 것입니다. –

1

가 : 보인다 당신이 쓴 것과 내가 썼던 것의 유일한 실용적인 차이점은 명시 적으로 하나의 상자에서 다른 상자로의 변화를 촉발시키는 것입니다. 한편

, 나뿐만 아니라 이런 일이 :

의미
$("#editEventContinents").change(function(){ // continents on change 
    return loadCountries("#editEventContinents", "#editEventCountries", "#editEventCities"); 
}); 

$("#editEventCountries").change(function(){ // countries on change 
    return loadCities("#editEventCountries", "#editEventCities"); 
}); 

, 그것은 않습니다 거의 같은, 맞죠?

내 문제는 실제로 테이블 행을 편집하여 결과적으로 업데이트 할 때입니다. 드롭 다운이 실패하는 곳입니다. 대륙 드롭 다운 상자에서 변경 이벤트를 트리거하지 않습니다

loadContinents("#editEventContinents"); 
$("#editEventContinents").val(response.eventData.continentId); 

같은 것을 사용

. 그리고 명시 적으로 결과가 좋지 않은 경우 국가를로드해도 선택한 개체가 식별되지 않습니다. 즉, 쿼리 문자열이 백엔드에 비어있게되면 모든 엉망이 발생합니다.

관련 문제