问题描述

在 Web 开发中,使用 Ajax 来提交表单,比如注册页面的注册信息表单的时候,经常遇到一个令人头疼的问题:用户名或 Email 经常要用到 Ajax 异步提交到后台判断。触发这一事件可由 文本输入控件失去焦点 onblur 和点击提交表单 Submit 按钮来完成。

第一种方法很容易实现,input 输入框失去焦点后,可以等待 Ajax 从后台返回的回应信息,这样一来就有一段时间来缓冲。

第二种方法则不好办了,提交前必须在前台判断所有的表单信息是否合法,包含 Ajax 异步判断。因为 Ajax 提交的请求因网络等因素总需要一小段时间来等待回应,不可能立即返回,所以,应如何做到按下提交按钮后,能得到等待 Ajax 请求的回应信息,判断这些表单信息来决定是否让这个表单提交呢。

解决方法之一

使用 jQuery Form Plugin来验证整个表单,一次性使用 Ajax 方式验证所有的表单信息。

第一步:安装插件。下载 jQuery 库和 jquery.form.js插件。

第二步:前台代码:


$(document).ready(function() { var options = { target: '#output1', // 显示服务器回应信息的目标元素 beforeSubmit: showRequest, // 预提交反馈,即前台 JS 判断方法 success: showResponse // 服务器回馈信息处理方法 // 其它可选方法: //url: url // 重新指定表单的提交地址 //type: type // 重新设置 form 表单的 method 属性值:'get' or 'post' //dataType: null // 服务器回应信息类型: 'xml', 'script', or 'json' //clearForm: true // 提交成功后清空表单域 //resetForm: true // 提交成功后重置表单域 // $.ajax 选项也可以在此使用,例如: //timeout: 3000 }; // 使用 'ajaxForm' 绑定表单 $('#myForm1').ajaxForm(options); }); // 预提交反馈,即前台 JS 判断方法 function showRequest(formData, jqForm, options) { // formData is an array; here we use $.param to convert it to a string to display it // but the form plugin does this for you automatically when it submits the data var queryString = $.param(formData); // jqForm is a jQuery object encapsulating the form element. To access the // DOM element for the form do this: // var formElement = jqForm[0]; alert('About to submit: \n\n' + queryString); // here we could return false to prevent the form from being submitted; // returning anything other than false will allow the form submit to continue return true; } // 服务器回馈信息处理方法 function showResponse(responseText, statusText, xhr, $form) { // for normal html responses, the first argument to the success callback // is the XMLHttpRequest object's responseText property // if the ajaxForm method was passed an Options Object with the dataType // property set to 'xml' then the first argument to the success callback // is the XMLHttpRequest object's responseXML property // if the ajaxForm method was passed an Options Object with the dataType // property set to 'json' then the first argument to the success callback // is the json data object returned by the server alert('status: ' + statusText + '\n\nresponseText: \n' + responseText + '\n\nThe output div should have already been updated with the responseText.'); }

最后一步,在后台提供一份和前台一样的验证方法。这是最后一首防线,所以很重要,甚至于前台的验证都可以不写,仅作文字说明的提示信息即可。建议使用 JSON 格式的 Response 信息,Ajax 返回到前台后作相应的处理即可。

解决方法之二

在检测所有表单时,无论结果如何,最后 return false; 以防止表单提交。然后在 Ajax 传回结果中使用 $("form").submit(); 方法来提交,此方法后来才想到,在此补上。

==================================================

以上仅是个人思路,具体实例请参考官网 Examples