2012-09-17 2 views
3

아래의 JSON 데이터가 있는데 AJAX JSON 응답의 일부 데이터와 함께 jQuery를 사용하여 div HTML을 작성하려고합니다. div이 성공 코드 내부에 생성됩니다 :JQuery 및 JSON 데이터를 사용하여 사업부 만들기

<script type="text/javascript"> 
    $(document).ready(function() { 
     $("#add-notes-form").submit(function(e){ 
      e.preventDefault(); 
      $.ajax({ 
       type: 'POST', 
       url: '<?php the_permalink(); ?>', 
       dataType: 'json', 
       data: $("#add-notes-form").serialize(), 
       success: function(result){ 
        $("#tab7 form").after("Code needs to go here"); 
       } 
      }); 
     }); 
    }); 
</script> 

JSON 데이터 :

{"comment_ID":"2", 
"comment_post_ID":"396", 
"comment_author":"Me", 
"comment_author_email":"[email protected]", 
"comment_author_url":"http:\//gmail.com", 
"comment_author_IP":"", 
"comment_date":"2012-09-17 09:21:19", 
"comment_date_gmt":"2012-09-17 16:21:19", 
"comment_content":"This is a killer Note. 4", 
"comment_karma":"0", 
"comment_approved":"1", 
"comment_agent":"", 
"comment_type":"note", 
"comment_parent":"0", 
"user_id":"1"} 

html로 내가 만들려고 해요을 :

<div id="comment-2" class="binder-user-note"> 
    <a href="?delete=2" id="close-note"></a> 
    <h1>I added this on: Monday 17th September 2012</h1> 
    <p>This is a killer Note. 2</p> 
    <a href="edit?2" id="editnote"></a> 
</div> 

내가 지금까지 무엇을 가지고 :

<div id="comment-'+response.comment_ID+'" class="binder-user-note"> 
    <a href="?delete='+response.comment_ID+'" id="close-note"></a> 
    <h1>I added this on: '+response.comment_date+'</h1> 
    <p>'+response.comment_content+'</p> 
    <a href="edit?'+response.comment_ID+'" id="editnote"></a> 
</div> 

response이 개체입니다.

답변

5
success: function(result){ 
    var jSon = result.Data; 
    var div = $("<div></div>") 
      .attr("id", "comment" + jSon.comment_ID) 
      .addClass("binder-user-note"); 
    var a = $("<a></a>") 
      .attr("href", "?delete=" + jSon.comment_ID) 
      .attr("id", "close-note"); 
    $("<h1></h1>").text("I added this on: " + jSon.comment_date) 
      .appendTo(a); 
    $("<p></p>").text(jSon.comment_content) 
      .appendTo(a); 
    $("<a></a>") 
      .attr("href", "edit?" + jSon.comment_ID) 
      .attr("id", "editnote") 
      .appendTo(a); 
    a.appendTo(div) 
    $("#tab7 form").after(div); 
} 
2

나는 항상 그와 같은 코드를 발견했습니다. 개인적으로 나는 YMMV, 이런 식으로 뭔가를 선호 :

success:function(result){ 
    var html = "<div id='comment-"+result.comment_ID+"' class='binder-user-note'>" + 
       "<a href='?delete="+result.comment_ID+"' id='close-note'></a>" + 
       "<h1>I added this on: "+result.comment_date+"</h1>" + 
       "<p>"+result.comment_content+"</p>" + 
       "<a href='edit?"+result.comment_ID+"' id='editnote'></a>" + 
       "</div>"; 

    $("#tab7 form").after(html); 
    $('#add-notes-form textarea').attr('value',''); 
} 

이 즐겨