我想在這裏做一些Ajax和jQuery,同時在同一頁面上提交表單。我讀了以下主題,開始了我想做的事(這是由幾個很好的例子):jQuery AJAX submit form用JQuery阻止重定向 - 我做錯了什麼?
這裏是我的HTML文件:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>jQuery File Tree Demo</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<script src="jquery.js" type="text/javascript"></script>
<script src="addTag.js" type="text/javascript"></script>
</head>
<body>
<form id="form_addtag" method="post" name="form_addtag" action="add_tag.php">
<legend>Add a tag</legend>
<input type="text" name="tag_name" id="tag_name" class="text" size="30" placeholder="Tag Name" />
<input type="text" name="tag_text_color" id="tag_text_color" class="text" size="6" placeholder="#ffffff"/>
<input type="text" name="tag_bg_color" id="tag_bg_color" class="text" size="6" placeholder="#000000" />
<button type="submit" id="button_save_tag">Add</button>
</form>
</body>
</html>
而且JS文件:
$("form_addtag").submit(function(e) {
e.preventDefault();
var url = "add_tag.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("form_addtag").serialize(), // serializes the form's elements.
});
});
執行完美:我可以填寫表單,點擊提交按鈕,它會將所有字段傳遞給add_tag.php。不過,我總是在mydomain.com/add_tag.php結束,而我想留在第一頁。
是的,這也是重要的一點! – Pointy
將函數放在$(document).ready()塊中解決了我的問題。謝謝 ! – Shadeslayer
太棒了,很高興我能幫到你。 – j08691