2011-09-22 3 views
1

jQuery 코드를 개선하려고합니다.jQuery를 사용하여 데이터 직렬화

코드 조각이 처리를 위해 다른 PHP 페이지에 데이터를 제출하고 있습니다.

현재 양식에서 제출 된 데이터를 가져 와서 페이지의 사용자 지정 데이터 특성에서 데이터를 가져옵니다.

여기에 코드

// Add new comment to nit on comment.php page 

$('#new_comment_form').bind('submit', function(e) { 

     // Prevent default 
     e.preventDefault(); 

     var commentNitId = $('#left_content').attr('data-nit-id'); 

     var commentData = 'nit_id=' + commentNitId + '&new_comment_text=' + $('textarea.new_comment').val(); 

     $.ajax({ 
      type: "POST", 
      url: "ajax/addComment.php", 
      data: commentData, 
      dataType: "json", 
      success: function(comment_response) { 

       // Code upon success 

      }, 
      error: function() { 
          // Error 
       alert("Error adding comment"); 
      } 
     }); 
    }); 

형태로 제출할 준비가 데이터를 직렬화하는 더 나은 ("깔끔한") 방법이 있는지 난 그냥 궁금 해서요입니까?

친절 감사를

누가 복음

답변

4

예. 객체 (표준 Javascript 객체)를 $.ajaxdata 옵션으로 제공하면 jQuery가 직렬화를 처리합니다.

$.ajax({ 
    type: "POST", 
    url: "ajax/addComment.php", 
    data: { 
     nit_id: commentNitId, 
     new_comment_text: $('textarea.new_comment').val() 
    }, 
    dataType: "json", 
    success: function (comment_response) { 

     // Code upon success 
    }, 
    error: function() { 
     // Error 
     alert("Error adding comment"); 
    } 
}); 

이 기능을 사용하려면 내부적으로 사용되는 기능이 jQuery.param입니다. 따라서 :

jQuery.param({ 
    nit_id: 5, 
    new_comment_text: 'foobar' 
}); 
// output: "nit_id=5&new_comment_text=foobar" 

여기에는 필요에 따라 이스케이프 문자가 추가되었습니다.

0

은 JQuery와 직렬화()와 serializeArray() 함수를보고하십시오. 양식 데이터를 얻을 수있는 깔끔한 방법을 제공합니다.

+0

안녕하세요 Pipalayan,이 기능을 살펴 보았지만 폼 요소와 데이터 특성을 기반으로 직렬화 된 배열을 만들면 문제가 발생합니다. 두 항목을 어떻게 병합합니까? 다시 한 번 감사드립니다! – Luke

+0

@LukeCoulton 불행히도 데이터 속성을 기반으로 serialize 된 배열을 가져 오는 간단한 방법은 없습니다. {serializeArray()는 "name"특성}을 기반으로 배열을 제공합니다. 다른 사용자 정의 속성의 경우 양식 요소를 반복하여 값을 찾아야합니다. –

0
$.ajax({ 
      dataType: 'json', 
      type:'post', 
      url: "ajax/addComment.php", 
      data:$(this).parents('form:first').serialize(), 
          success: function (comment_response) { 

            // Code upon success 
           }, 
          error: function() { 
             // Error 
           alert("Error adding comment"); 
          }, 
     }); 
관련 문제