[英]AJAX: Submitting a form without refreshing the page
我有一个类似于以下的表格:
<form method="post" action="mail.php" id="myForm">
<input type="text" name="fname">
<input type="text" name="lname">
<input type="text" name="email">
<input type="submit">
</form>
我是AJAX的新手,我想要完成的是当用户点击提交按钮时,我想让mail.php
脚本在幕后运行而不刷新页面。
我试过类似下面代码的东西,然而,它似乎仍然像以前一样提交表单而不是像我需要它(在幕后):
$.post('mail.php', $('#myForm').serialize());
如果可能的话,我想帮助使用AJAX实现这一点,
提前谢谢了
您需要阻止默认操作(实际提交)。
$(function() {
$('form#myForm').on('submit', function(e) {
$.post('mail.php', $(this).serialize(), function (data) {
// This is executed when the call to mail.php was succesful.
// 'data' contains the response from the request
}).error(function() {
// This is executed when the call to mail.php failed.
});
e.preventDefault();
});
});
您没有提供完整的代码,但听起来问题是因为您在提交表单时执行$.post()
,但没有停止默认行为。 尝试这个:
$('#myForm').submit(function(e) {
e.preventDefault();
$.post('mail.php', $('#myForm').serialize());
});
/**
* it's better to always use the .on(event, context, callback) instead of the .submit(callback) or .click(callback)
* for explanation why, try googling event delegation.
*/
//$("#myForm").on('submit', callback) catches the submit event of the #myForm element and triggers the callbackfunction
$("#myForm").on('submit', function(event, optionalData){
/*
* do ajax logic -> $.post is a shortcut for the basic $.ajax function which would automatically set the method used to being post
* $.get(), $.load(), $.post() are all variations of the basic $.ajax function with parameters predefined like 'method' used in the ajax call (get or post)
* i mostly use the $.ajax function so i'm not to sure extending the $.post example with an addition .error() (as Kristof Claes mentions) function is allowed
*/
//example using post method
$.post('mail.php', $("#myForm").serialize(), function(response){
alert("hey, my ajax call has been complete using the post function and i got the following response:" + response);
})
//example using ajax method
$.ajax({
url:'mail.php',
type:'POST',
data: $("#myForm").serialize(),
dataType: 'json', //expects response to be json format, if it wouldn't be, error function will get triggered
success: function(response){
alert("hey, my ajax call has been complete using the ajax function and i got the following response in json format:" + response);
},
error: function(response){
//as far as i know, this function will only get triggered if there are some request errors (f.e: 404) or if the response is not in the expected format provided by the dataType parameter
alert("something went wrong");
}
})
//preventing the default behavior when the form is submit by
return false;
//or
event.preventDefault();
})
试试这个:
$(function () {
$('form').submit(function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
$('#result').html(result);
}
});
}
return false;
});
});
尝试这个..
<form method="post" action="mail.php" id="myForm" onsubmit="return false;">
要么
加
e.preventDefault();
在你的click
功能
$(#yourselector).click(function(e){
$.post('mail.php', $(this).serialize());
e.preventDefault();
})
如果您使用输入类型作为提交<input type="submit" name="submit" value="Submit">
则需要阻止默认操作。
通过将$("form").submit(...)
附加到提交处理程序,这将提交表单(这是默认操作)。
如果不希望此默认操作使用preventDefault()
方法。
如果您使用的不是提交,则无需阻止默认。
$("form").submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'save.asmx/saveData',
dataType: 'json',
contentType:"application/json;charset=utf-8",
data: $('form').serialize(),
async:false,
success: function() {
alert("success");
}
error: function(request,error) {
console.log("error");
}
执行此操作的现代方法(也不需要jquery)是使用fetch API 。 较旧的浏览器不支持它 ,但如果这是一个问题,则有一个polyfill 。 例如:
var form = document.getElementById('myForm');
var params = {
method: 'post',
body: new FormData(form),
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
};
form.addEventListener('submit', function (e) {
window.fetch('mail.php', params).then(function (response) {
console.log(response.text());
});
e.preventDefault();
});
看一下JQuery Post文档。 它应该会帮助你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.