2010-06-03 20 views
11

Tôi có một biểu mẫu đơn giản mà hiện tại tôi đang đăng lại máy chủ để cập nhật biệt hiệu. Tôi cần thêm mã jquery nào (không thay đổi biểu mẫu) để trang không làm mới, nhưng thay vào đó jquery sẽ đăng biểu mẫu ở chế độ nền và sau đó bật lên một thông báo cảnh báo chứa trả lời từ máy chủ?Làm thế nào để bạn ghi đè lên một biểu mẫu html hiện có để sử dụng jquery để gửi biểu mẫu?

<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> 

Trả lời

23

try reading this.

hoặc

$("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

Bạn cần sử dụng jQuery để liên kết với sự kiện "gửi" và ngăn tác vụ mặc định. Nó sẽ hiệu quả hơn một chút nếu hình thức và nickname của bạn đầu vào sử dụng id 's ngoài tên của họ:

<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> 
Các vấn đề liên quan