Php Ajax表单问题
我正在尝试做一个简单的ajax表单帖子。我认为我的代码在$.ajax行中存在问题。一旦代码到达$.ajax部分,console.log()就无法工作,表单只是按照惯例重定向到ajax-report-comment.php页面,而不是通过ajax。在此部分之前,my console.log函数报告数据,不重定向到页面 有人知道我做错了什么吗?基本上,在成功时,我希望它能够提醒用户报告成功 提前谢谢 代码:Php Ajax表单问题,php,jquery,ajax,Php,Jquery,Ajax,我正在尝试做一个简单的ajax表单帖子。我认为我的代码在$.ajax行中存在问题。一旦代码到达$.ajax部分,console.log()就无法工作,表单只是按照惯例重定向到ajax-report-comment.php页面,而不是通过ajax。在此部分之前,my console.log函数报告数据,不重定向到页面 有人知道我做错了什么吗?基本上,在成功时,我希望它能够提醒用户报告成功 提前谢谢 代码: $(文档).ready(函数(){ $('form.ajax')。在('submit',f
$(文档).ready(函数(){
$('form.ajax')。在('submit',function()上{
var that=$(此),
url=that.attr('action'),
method=that.attr('method'),
数据={};
that.find('[name]')。每个(函数(索引,值){
var that=$(此),
name=that.attr('name'),
value=that.val();
数据[名称]=值;
});
$.ajax({
url:url,
类型:类型,
数据:数据,
成功:功能(响应){
控制台日志(响应);
}
});
返回false;
});
});
我很确定返回false现代版本的jQuery不推荐使用code>取消默认操作(如果您使用migrate
插件,您将看到有关此操作的警告),因此您应该使用:
$('form.ajax').on('submit',function(e) {
e.preventDefault();
// the rest of your code
我想对@jeroen的回答补充一点:
按照他的建议使用,但也要检查
您可以替换整个代码块(来自上面的代码):
与:
多亏了Jeroen,我才能够找到匿名函数的错误。我有一个方法,我应该在var中有类型
更正了功能正常的js代码:
$(document).ready(function(){
$('form.ajax').on('submit',function(e) {
e.preventDefault();
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response) {
console.log(response);
}
});
return false;
});
});
这可能是最近我在return false
和preventDefault()
工作时遇到类似问题的原因。嗨,Jeroen,我按照你的指示做了,看起来我有一个错误:Uncaught ReferenceError:type未定义demo.php:31(匿名函数)demo.php:31 x.event.dispatch jquery-1.10.2.js:5095 v.handle将尝试序列化方法。谢谢你的意见。
// Replace this entire block with jQuery's serialize
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
var data = $(this).serialize();
$(document).ready(function(){
$('form.ajax').on('submit',function(e) {
e.preventDefault();
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response) {
console.log(response);
}
});
return false;
});
});