2016-07-28 1 views
1

Ajax를 처음 사용합니다. "이름"과 버튼이있는 템플릿이 있습니다. 버튼을 클릭하면 이름과 버튼이 일부 메시지로 바뀝니다. 내 코드가 완벽하게 작동합니다. 아약스 :Ajax를위한 더 좋은 디자인은 div를 다른 div로 바꿉니다.

$('#fulfillButton').bind('click',function() { 
     $.ajax({ 
      type : "GET", 
      contentType : "application/json; charset=utf-8", 
      url : "/order/${orderID}", 
      dataType : "json", 
      cache: false, 
      timeout: 12000, 

      success: function (data) { 
        alert("success"); 
      }, 

      error: function (data,textStatus) { 
       if(textStatus == "timeout") 
       { 
        $('#main-panel').replaceWith('<div class="error-message">' + "Timeout, please clcik the button beblow to scan again!" + '</div>'); 
       } 
       else 
       { 
        var responseText = data.responseText; 
        var jsonErrorMessage = JSON.parse(responseText); 
        $('#main-panel').replaceWith('<div class="error-message">' + jsonErrorMessage["body"] + '</div>'); 
       } 
      }, 
     }); 

HTML :

 <div id="main-panel"> 
     <div class="full-name"> 
      ${name} 
     </div> 
     <div id 
     <button id="fulfillButton" type="button" class="action-button shadow animate fulfill-button-color"> 
      FulFill 
     </button> 
    </div> 
    <button id="goBackButton" type="button" class="go-back-button"> 
     Go Back 
    </button> 

하지만 지금은 더 나은 디자인을 찾고 있어요. 알 수 있듯이

$('#main-panel').replaceWith('<div class="error-message">' + jsonErrorMessage["body"] + '</div>'); 

그러나 여기서는 div 태그를 넣지 않기 위해 로직으로 뷰 요소가 산재 해있는 것을 피하고자합니다. DIV를 HTML에 넣고 싶습니다. 아니면 JS에 "error_message"스타일을 적용하여 기존 DIV를 사용할 수 있습니까? 그렇다면 어떻게 실제로 코드를 작성할 수 있습니까?

답변

1

왜 오류 메시지가 HTML에서 div를 추가하지 으로 <div class="error-message" id="someID' hidden>...</div>을 숨겨 (그들에게 어떤 ID를 제공, main-panel 내부 것이 있고 Error2error1, 말할 수) 당신은 오류 대신을 얻을 때 replace 그냥 전화

error: function (data,textStatus) { 
    $('#main-panel').find('*').not('.error-message').remove();//Remove everything except from the error-message divs 
    if(textStatus == "timeout") 
    { 
     $('#error1').html('Timeout, please clcik the button beblow to scan again!'); 
     $('#error1').show(); 
    } 
    else 
    { 
     var responseText = data.responseText; 
     var jsonErrorMessage = JSON.parse(responseText); 
     $('#error2').html(jsonErrorMessage["body"]); 
     $('#error2').show(); 
    } 
}, 
+0

는 내 제안에 따라 변경 주어진 함수 내 대답을 업데이트했습니다. –

+0

나는 실제로 '# main-panel'전체를 제거하고 오류 메시지에 대해 새 div (숨김)를 만들 수 있습니까? – user3369592

+0

물론,'# main-panel' 외부의 오류 div를 숨김으로 추가 할 수 있습니다. 그런 다음 오류가 발생하면'$ ('# main-panel'). remove(); $ ('# error1'). show();'이것이 당신이 원하는 것입니까? –

1

많은 솔루션을 사용할 수 있습니다. 나는 두 가지를 준다 :

첫번째 해결책 (javascript를 보라)은 작은 것들 (예 : 에러 메시지)에 좋다.

두 번째는 양식을 동적으로 만드는 것과 같은 지연된 작업에 적합합니다. 이를 템플리트라고합니다.

// Solution 1 
 

 
$('#fulfillButton').bind('click',function() { 
 
    $('#main-panel').replaceWith($('<div />').addClass('error-message').html('Some content here. This is added by dynamically creating the div, adding error message class and adding content'));  
 
}); 
 

 
// Solution 2 
 
$('#fulfillButton2').bind('click',function() { 
 
    $('#main-panel').replaceWith($("#error-message-template").clone().removeClass('hidden').html('Some content here 2. This is added by cloning an existing hidden div, removing the hidden class and replacing the content.'));  
 
});
.error-message{ 
 
    border: 1px solid #f00; 
 
} 
 

 
#main-panel{ 
 
    border: 1px solid #cccccc; 
 
} 
 

 
.hidden 
 
{ 
 
    display: none 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="main-panel"> 
 
     <div class="full-name"> 
 
      ${name} 
 
     </div> 
 
     
 
     <button id="fulfillButton" type="button" class="action-button shadow animate fulfill-button-color"> 
 
      
 
      FulFill 
 
     </button> 
 
    <button id="fulfillButton2" type="button" class="action-button shadow animate fulfill-button-color"> 
 
    Fulfill 2 
 
    </button> 
 
    </div> 
 
    <button id="goBackButton" type="button" class="go-back-button"> 
 
     Go Back 
 
    </button> 
 

 
<div id="error-message-template" class="error-message hidden"> 
 
</div>

관련 문제