所以,这就是我遇到的问题:我正在尝试使用jQuery和ajaxForm (表单插件)提交表单。但是,当我单击submit按钮时,我没有得到任何响应(也没有错误)。表单上有必填字段,我当前期望的响应是一个警报,通知我缺少一个(或多个)必填字段,并详细说明哪些字段需要数据才能成功完成表单。
应用程序是用CodeIgniter构建的,这就是表单操作看起来是这样的原因。
下面是我的jQuery代码:
$(function () {
$("#div_id").dialog({
autoOpen: false,
closeOnEscape: true,
modal: true,
width: 600,
title: "A Title",
buttons: {
"SUBMIT": function() {
$("#form_id").ajaxForm({
dataType: "json",
success: function(response) {
response = $.parseJSON(response);
alert(response['message']);
}
});
},
"CANCEL": function() {
// Some clean up here
$("#div_id").dialog("close");
}
},
close: function() {
// Some clean up here
$("#div_id").dialog("close");
}
});
});下面是表单标签:
<form method="post" id="form_id" action="/controller/function">另外,我正确地链接了ajaxForm插件。因此,问题并不存在于此。我还在学习jQuery,任何帮助我都很感激。我也一直在查阅http://www.malsup.com/jquery/form/和jQuery文档,但都没有找到答案。
提前谢谢你!
发布于 2013-03-29 06:19:46
我已经解决了这个问题。对于任何在未来找到这个问题和答案的人来说,这是我必须做的:
首先,这是一个示例onload函数(假设您使用的是jQuery):
$(function () {
$("#div_id").dialog({
autoOpen: false,
closeOnEscape: true,
modal: true,
width: 600,
title: "Your Title",
buttons: {
"SUBMIT": function() { $("#form_id").submit() },
"CANCEL": function() {
// Other clean-up functions here
$("#div_id").dialog("close");
}
},
close: function() {
// Other clean-up functions here
$("#div_id").dialog("close");
}
});
});确保您的submit()调用被放在
function(){ }当我不这样做的时候,页面一加载,我的表单就一直试图提交自己。当我将它们放在上面的代码行中时,它停止了。
接下来的一切都是在上面的onload函数之后进行的。
其次,设置您的ajaxForm选项变量:
var ajaxFormOptionsVariable = {
beforeSubmit: ajaxFormPreSubmitFunction,
success: ajaxFormPostSubmitFunction,
type: "post",
dataType: "json"
};现在,简单介绍一下您的ajaxForm选项。显而易见(但可能不是这样)的是,您可以随心所欲地命名您的变量。可能不太明显的是,对于页面上的每个表单对话框,您都需要一个单独的变量。注意你的名字!
命名为"beforeSubmit“函数和"success”函数的函数也可以命名为您想要的任何名称。如果您有需要不同处理的不同表单,则需要为每个表单定义不同的函数。再说一次,要注意你的命名!
您的"beforeSubmit“函数是可选的。你也可以用"get“来表示”类型“,我知道"dataType”还有其他的选项,但我不知道它们(目前也不需要它们)。但是,如果您不希望将数据作为json对象提交,那么请对插件进行一些研究,以找到您的选择。
第三,实例化ajaxForm对象:
$('#form_id').ajaxForm(ajaxFormOptionsVariable);第四,定义你的"beforeSubmit“和"success”函数:
function ajaxFormPreSubmitFunction(response, statusText, xhr, $form) {
// Whatever processing you want to do before the form is submitted -
// probably validation
}
function ajaxFormPostSubmitFunction(response, statusText, xhr, $form) {
// Whatever processing you want to do after the form is submitted
// This is where displaying a message to the user happens
}简单介绍一下提供给回调函数的参数。首先,响应是您从服务器返回的所有内容的位置。其次,您不需要
response = $.parseJSON(response);响应会被自动解析。在我的脚本的post submit回调中,我实际上返回了一个数组,其中一个元素是true/false值,另一个是我想要显示给用户的任何消息,如下所示:
if (response['result'] == true) {
$("#success_dialog").html(response['message']);
$("#success_dialog").dialog("open");
}
else {
$("#error_dialog").html(response['message']);
$("#error_dialog").dialog("open");
}所以,就是这样。为了完成这项工作,我的代码都错了。在经历了一些挫折之后,我让它工作了。我想回来分享它,这样问题就可以标记为已回答(防止任何人在这个问题上浪费时间,因为我已经解决了它),并帮助任何人谁可能会在未来遇到这条消息。
https://stackoverflow.com/questions/15601335
复制相似问题