Ajax表单重载页面,而不是在后台工作
Ajax form reloading page instead of working in the background
首先,根据其他建议,我尝试过移动preventDefault(),但没有成功。
我的反馈表单使用JavaScript将表单字段传递给"process.php"并返回相关消息(即:" success "或"fail")
它正在做它的工作,但不是停留在同一个页面'feedback.php',而是加载'process.php'页面。{"数据":"数据值"}
下面是代码:$(document).ready(
function(){
$('form').submit(
function(event){
var formData =
{
'name' : $('input[name=name]').val(),
'page' : $('input[name=page]').val()
};
$('.form-group').removeClass('has-error'); // remove the error class
$('.error').remove(); // remove the error text
event.preventDefault();
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'process.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
.done(function(data){
if ( ! data.success)
{
if (data.errors.name)
{
$('#name-group').addClass('has-error'); // add the error class to show red input
$('#nameField').append(data.errors.name); // add the actual error name under our input
}
}
else
{
$('form').append('<div class="buttonError">Message Sent!</div>');
form.myButton.disabled = true;
}
}
);
.fail(function(data){
$('form').append('<div class="buttonError">Failed!</div>');
}
console.log(data);
);
event.preventDefault();
}
);
});
看起来像调用$的语法错误。在Ajax中,应该这样更正:
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'process.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
}).done(function(data){
if ( ! data.success)
{
if (data.errors.name)
{
$('#name-group').addClass('has-error'); // add the error class to show red input
$('#nameField').append(data.errors.name); // add the actual error name under our input
}
}
else
{
$('form').append('<div class="buttonError">Message Sent!</div>');
form.myButton.disabled = true;
}
}).fail(function(data){
$('form').append('<div class="buttonError">Failed!</div>');
console.log(data);
});
删除HTML文件中表单标记中的方法和操作。看起来不错。
相关文章:
- Chrome扩展程序在后台工作
- ngRoute 在 angularjs 中作为依赖项包含在后台时如何工作
- 无法通过“&”使nodejs在后台工作
- jQuery Mobile App 的后台工作线程
- Chrome 扩展程序:无法让消息传递在后台脚本和内容脚本之间正常工作
- addEventListener 如何在后台工作
- heroku上的后台工作网络是如何知道的's结束了
- 没有web工作程序的Javascript后台处理
- querySelector是如何在后台工作的
- Javascript-事件监听器如何在后台工作
- jQuery点击事件不工作时,全屏iframe在后台
- 改变后台javascript功能不工作
- 在node.js中使用工作/后台进程vs .异步调用
- Ajax表单重载页面,而不是在后台工作
- 为什么css后台jQuery代码不工作jQuery设置多个css值
- 如何使一个phonegap构建应用程序在后台工作
- 使用canvas创建桌面通知图像,只有一个图像可以从后台页面工作
- force.start (d3.js) 是否在后台工作
- selenium (Firefox后台),sendkeys工作,但不聚焦
- 在HTML5应用程序中下载后台数据到浏览器数据库- settimeout vs工作线程