2017-12-13 1 views
0

설명하는 것이 약간 까다 롭습니다. 최선을 다할 것입니다.AJAX에서 동적으로 HTML 행을 생성합니다.

저는 AJAX 및 jQuery에서 정적 HTML 페이지를 사용하는 스프링 기반 웹 사이트를 운영합니다. 나는 항상 크기가 다를 HTML 페이지에 몇 가지 정보를 제시하고자합니다.

나는 이와 같은 테이블이 있습니다

test table

그래서, 국가와 사용자의 수에 따라이 API에서 반환 , 나는 다른 갖고 싶어 (끔찍한 디자인을 신경 쓰지 않는다) 행 수.

내가 현재이 양식을 제출 한 후 HTML 코드를 삽입하기 위해 jQuery를 기능을 사용하고 있습니다 : 이와 같은 enter image description here

: 응답은 API로부터받은

$('#stats').submit((event) => { 
    event.preventDefault(); 
    $.ajax({ 
     url: '/api/stats/' + $(event.currentTarget).serialize(), 
     type: 'GET', 
     success(msg) { 
      // language=HTML 
      $('#result').html(` 
      <div class="container"> 
       <h2>Country stats:</h2> 
       <div class="panel panel-group"> 
        <table> 
         <thead> 
          <tr> 
           <th>Country</th> 
           <th>Users</th> 
          </tr> 
         </thead> 
         <tbody> 
          <tr> <!-- I want to generate here the right amount of rows --> 
           <td>Test</td> 
           <td>2</td> 
          </tr> 
         </tbody> 
        </table> 
       </div> 
      </div>`); 
     }, 
     error() { 
      $('#result').html("<div class='alert alert-danger lead'>ERROR</div>"); 
     }, 
    }); 

은 다음과 같습니다

{ 
"countries": 
    [{"data":xx,"users":xx}, 
    {"data":xx,"users":xx}], 
"other data": 
    [whatever] 
} 

등등.

N이 국가 배열의 크기 인 경우 어떻게 N 행을 렌더링 할 수 있습니까? ,

for(var i = 0; i < msg.countries.length; i++){ 
    html += "<tr><td>" + msg.countries[i].data + "</td><td>" + msg.countries[i].users + "</td></tr>"; 
} 

을 마지막으로 HTML의 끝을 추가로 설정 : 당신의 행을 추가, 그리고

var html = `<div class="container"> 
      <h2>Country stats:</h2> 
      <div class="panel panel-group"> 
       <table> 
        <thead> 
         <tr> 
          <th>Country</th> 
          <th>Users</th> 
         </tr> 
        </thead> 
        <tbody>`; 

을 :

+2

html을 만드시겠습니까? 'var rows = ''; msg.countries.forEach ((country) => rows + = ""+ country.data + "");'행 결과를'$ result'에 연결 하시겠습니까? – FrankerZ

+0

알았어, 쉬웠다. 동의 할 수 있도록 답변으로 게시 해주세요. – dari1495

답변

3

하나의 해결책은 3 부분에서 "HTML"컨텐츠를 구축 할 수 있었다 :

$('#stats').submit((event) => { 
    event.preventDefault(); 
    $.ajax({ 
    url: '/api/stats/' + $(event.currentTarget).serialize(), 
    type: 'GET', 
    success(msg) { 
     // language=HTML 

     // The begin of your html bloc 
     var result = ` 
      <div class="container"> 
       <h2>Country stats:</h2> 
       <div class="panel panel-group"> 
        <table> 
         <thead> 
          <tr> 
           <th>Country</th> 
           <th>Users</th> 
          </tr> 
         </thead> 
         <tbody> 
        `; 

     // Just get your countries array here and loop, this can be wrong 
     $.each(response.countries, function() { 
      // build each row as you need 
      result += '<tr>' + 
         '<td>' + this.data + '</td>' + 
         '<td>' + this.users + '</td>' + 
        '</tr>'; 
     }); 

     // The end of your html bloc 
     result += `    
        </tbody> 
       </table> 
      </div> 
     </div> 
       `; 

     $('#result').html(result); 
    }, 
    error() { 
     $('#result').html("<div class='alert alert-danger lead'>ERROR</div>"); 
    }, 
}); 
: (가), 국가 배열의 크기에 따라, 당신의 블록의 블록의 다음 말을 각 행에 대한 루프를 시작

찾고 계신 것이 맞습니까?

+0

html 블록의 끝에서 ' 테스트 '을 잊지 마세요! – Luke

+1

죄송합니다. 귀하가 anwser를 게시하기 전에 작성하기 시작했으나 빠릅니다! 그리고 나는 내 게시물을 편집했습니다.) –

+1

나는'$ .each'의 사용을 좋아합니다. 실제로 응답을 완료하려면'// your data' 부분을 살핀다. – showdev

2

그래서 같은 변수에 내 HTML의 나머지 부분을 할당합니다 요소 :

html += `</tbody> 
       </table> 
      </div> 
     </div>`; 
$('#result').html(html); 

희망이 있습니다.

관련 문제