使用jquery插件jquery.form.js,异步提交表单 1
Quick Start Guide
<form id="myForm" action="comment.php" method="post">
Name: <input type="text" name="name" />
Comment: <textarea name="comment"></textarea>
<input type="submit" value="Submit Comment" />
</form>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
// wait for the DOM to be loaded
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#myForm').ajaxForm(function() {
alert("Thank you for your comment!");
});
});
</script>
</head>
...
That's it!
When this form is submitted the name and comment fields will be posted to comment.php. If the server returns a success status then the user will see a "Thank you" message.
2.code Example
处理json
<form id="jsonForm" action="json-echo.php" method="post">
Message: <input type="text" name="message" value="Hello JSON" />
<input type="submit" value="Echo as JSON" />
</form>
JavaScript:
// prepare the form when the DOM is ready
$(document).ready(function() {
// bind form using ajaxForm
$('#jsonForm').ajaxForm({
// dataType identifies the expected content type of the server response
dataType: 'json',
// success identifies the function to invoke when the server response
// has been received
success: processJson
});
});
Callback function
function processJson(data) {
// 'data' is the json object returned from the server
alert(data.message);
}
处理xml
<form id="xmlForm" action="xml-echo.php" method="post">
Message: <input type="text" name="message" value="Hello XML" />
<input type="submit" value="Echo as XML" />
</form>
JavaScript:
// prepare the form when the DOM is ready
$(document).ready(function() {
// bind form using ajaxForm
$('#xmlForm').ajaxForm({
// dataType identifies the expected content type of the server response
dataType: 'xml',
// success identifies the function to invoke when the server response
// has been received
success: processXml
});
});
Callback function
function processXml(responseXML) {
// 'responseXML' is the XML document returned by the server; we use
// jQuery to extract the content of the message node from the XML doc
var message = $('message', responseXML).text();
alert(message);
}
处理html
JavaScript:
// prepare the form when the DOM is ready
$(document).ready(function() {
// bind form using ajaxForm
$('#htmlForm').ajaxForm({
// target identifies the element(s) to update with the server response
target: '#htmlExampleTarget',
// success identifies the function to invoke when the server response
// has been received; here we apply a fade-in effect to the new content
success: function() {
$('#htmlExampleTarget').fadeIn('slow');
}
});
});
参考来源:http://malsup.com/jquery/form/#getting-started
Andy_能力越到责任越大