2012-02-07 37 views
7

Tôi đang cố gắng sử dụng Javascript để gửi dữ liệu của biểu mẫu. Đây là html.onsubmit biểu mẫu html làm mới

<form onsubmit="post();"> 
//input fields here 
</form> 

Đây là Javascript cho hàm post().

var post = function() { 
alert('the form was submitted'); 
return false; 
} 

Vấn đề của tôi là Javascript chạy nhưng hình thức vẫn xử lý và làm mới trang ..

Tôi đặt mã return false; trong hy vọng nó sẽ ngăn chặn các hình thức từ sảng khoái.

Trả lời

12

Bạn sẽ phải đặt lại phần sai sau khi bài() chức năng trong xử lý onsubmit, như vậy:

<form onsubmit="post();return false;"> 
//input fields here 
</form> 
+0

tôi đã cố gắng đó và nó đã không làm việc! Nhưng bây giờ nó đang hoạt động, cảm ơn! – Frank

+0

Thật kỳ lạ khi nó không hoạt động trước đây. Có thể là một số lỗi cú pháp trong lần đầu tiên. Rất vui vì nó hiện đang hoạt động, rất vui được trợ giúp! –

+0

'

' thậm chí còn tốt hơn, xem câu trả lời của tôi. – gdoron

2

Bạn cần phải thực sự trả về false từ inline dom-0 xử lý của bạn. Vì vậy, thay đổi

onsubmit = "post();"> 

để

onsubmit = "return post();"> 

Hoặc bạn có thể cung cấp cho mẫu của bạn một id và làm điều này:

<form id="form1" onsubmit = "post();"> 

Sau đó, từ một địa điểm an toàn, trong đó dom bạn đã sẵn sàng :

document.getElementById("form1").onsubmit = post; 
2

Vì bạn thêm thẻ jQuery, đây nó là cách tốt nhất để làm điều này:
sự kiện không phô trương đính kèm

$('form').submit(function(){ 
     alert('the form was submitted'); 
     return false; 
    }); 

Bằng cách của bạn nó nên được;

<form onsubmit="return post();"> 
6

Giữ các js của bạn ra khỏi DOM.

<form id="myform" action="somepage.php" method="post"> 
//input fields 
</form> 

JQuery:

$('#myform').submit(function(event){ 
    alert('submitted'); 
    event.preventDefault(); 
}); 
1

Kể từ khi bài này được gắn thẻ với jQuery, tôi sẽ cung cấp các giải pháp sau đây:

$('form').submit(function(e){ 
    //prevent the form from actually submitting. 
    e.preventDefault(); 
    //specify the url you want to post to. 
    //optionally, you could grab the url using $(this).attr('href'); 
    var url = "http://mysite.com/sendPostVarsHere"; 
    //construct an object to send to the server 
    //optionally, you could grab the input values of the form using $(this).serializeArray() 
    var postvars = {}; 
    //call jquery post with callback function 
    $.post(url, postvars, function(response){ 
    //do something with the response 
    console.log(response); 
    }, 'json') 
}); 
+0

Nếu bạn chọn sử dụng serializeArray(), gán nó cho một biến và thực thi [Pointy Array -> Object function here] (http://stackoverflow.com/questions/7867441/form-keyvalue-pairs-jquery-plugin#answer -7867459) trước khi gửi nó đến máy chủ. –

Các vấn đề liên quan