发布在:Ajax

Ajax 与表单

在处理表单时,jQuery 的 ajax 功能尤其有用。它有许多优势,从序列化到简单的客户端验证(例如“抱歉,该用户名已被占用”),再到预过滤器(如下所述),还有更多!

link 序列化

在 jQuery 中序列化表单输入非常容易。本机支持两种方法:.serialize().serializeArray()。虽然这些名称相当不言自明,但使用它们有很多优势。

.serialize() 方法将表单数据序列化为查询字符串。要对元素的值进行序列化,它必须具有 name 属性。请注意,只有选中类型为 checkboxradio 的输入中的值才会被包含。

1
2
3
4
5
// Turning form data into a query string
$( "#myForm" ).serialize();
// Creates a query string like this:
// field_1=something&field2=somethingElse

虽然普通序列化很好,但有时如果发送对象数组而不是查询字符串,你的应用程序会工作得更好。为此,jQuery 有 .serializeArray() 方法。它与上面列出的 .serialize() 方法非常相似,只是它生成的是对象数组,而不是字符串。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// Creating an array of objects containing form data
$( "#myForm" ).serializeArray();
// Creates a structure like this:
// [
// {
// name : "field_1",
// value : "something"
// },
// {
// name : "field_2",
// value : "somethingElse"
// }
// ]

link 客户端验证

客户端验证与许多其他事情一样,使用 jQuery 非常容易。虽然有许多情况开发人员可以进行测试,但一些最常见的情况是:必需输入是否存在、用户名/电子邮件/电话号码等是否有效,或者选中“我同意……”框。

请注意,建议你对输入也执行服务器端验证。但是,能够在不提交表单的情况下验证某些内容通常会带来更好的用户体验。

话虽如此,让我们来看一些示例!首先,我们将看到检查必需字段是否没有任何内容是多么容易。如果没有,那么我们将return false,并阻止表单处理。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Using validation to check for the presence of an input
$( "#form" ).submit(function( event ) {
// If .required's value's length is zero
if ( $( ".required" ).val().length === 0 ) {
// Usually show some kind of error message here
// Prevent the form from submitting
event.preventDefault();
} else {
// Run $.ajax() here
}
});

让我们看看检查电话号码中是否存在无效字符是多么容易

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Validate a phone number field
$( "#form" ).submit(function( event ) {
var inputtedPhoneNumber = $( "#phone" ).val();
// Match only numbers
var phoneNumberRegex = /^\d*$/;
// If the phone number doesn't match the regex
if ( !phoneNumberRegex.test( inputtedPhoneNumber ) ) {
// Usually show some kind of error message here
// Prevent the form from submitting
event.preventDefault();
} else {
// Run $.ajax() here
}
});

link 预过滤

预筛选器是一种在发送每个请求之前修改 Ajax 选项的方法(因此,名称为prefilter)。

例如,假设我们希望通过代理修改所有跨域请求。使用预筛选器执行此操作非常简单

1
2
3
4
5
6
7
// Using a proxy with a prefilter
$.ajaxPrefilter(function( options, originalOptions, jqXHR ) {
if ( options.crossDomain ) {
options.url = "http://mydomain.net/proxy/" + encodeURIComponent( options.url );
options.crossDomain = false;
}
});

您可以在回调函数之前传入一个可选参数,该参数指定希望预筛选器应用于哪些dataTypes。例如,如果我们希望预筛选器仅应用于JSONscript请求,我们将会执行

1
2
3
4
5
6
// Using the optional dataTypes argument
$.ajaxPrefilter( "json script", function( options, originalOptions, jqXHR ) {
// Do all of the prefiltering here, but only for
// requests that indicate a dataType of "JSON" or "script"
});