2010-06-03 4 views
11

간단한 양식을 사용하여 현재 닉네임을 업데이트하기 위해 서버에 다시 게시하고 있습니다. 어떤 jquery 코드를 추가하여 폼을 변경하지 않고 페이지를 새로 고치지 않고 대신 jquery가 폼을 백그라운드에 게시 한 다음 서버에서 응답을 포함하는 경고 메시지를 팝업합니다.jquery를 사용하여 양식을 게시하려면 기존 html 양식을 어떻게 대체합니까?

<form method="post" action="http://www.myserver.com/update_nickname" name="input"> 
    Quick form to test update_nickname:<br> 
    New nickname:<input type="text" value="BigJoe" name="newNickname"><br> 
    <input type="submit" value="Submit"> 
</form> 

<script src="jquery-1.4.2.min.js" type="text/javascript"> </script> 

답변

23

try reading this.

또는

$("form").submit(function(e){ 
    var form = $(this); 
    $.ajax({ 
     url : form.attr('action'), 
     type : form.attr('method'), 
     data : form.serialize(), // data to be submitted 
     success: function(response){ 
      alert(response); // do what you like with the response 
     } 
    }); 
    return false; 
}); 
5

"제출"이벤트에 바인딩하고 기본 동작을 방지하려면 jQuery를 사용해야합니다. 양식 및 별명 입력이 이름에 추가 id 년대를 사용한 경우는 좀 더 효율적으로 될 것입니다 :

<script type="text/javascript"> 
    jQuery(function($){ 
     $("form[name=input]").submit(function(e){ 
     e.preventDefault(); // Keep the form from submitting 
     var form = $(this); 

     // Use the POST method to post to the same url as 
     // the real form, passing in newNickname as the only 
     // data content 
     $.post(form.attr('action'), { newNickname: form.find(':text').val() }, function(data){ 
      alert(data); // Alert the return from the server 
     }, "text"); 
     }); 
    }); 
</script> 
관련 문제