用于 AJAX 登录 UI 的 jQuery 插件






4.95/5 (13投票s)
学习如何构建一个提供 AJAX 登录界面的 jQuery 插件。
引言
登录是我们每天都会做的最频繁的活动之一。这是我们在互联网上保护和访问我们私人空间最常见的方式。可以理解的是,登录界面几乎成为所有 Web 应用程序的必备功能。既然登录界面是每个 Web 应用程序的必备功能,为什么不将其作为一个插件,让开发者可以直接将其插入代码并开箱即用获得一个可用的登录界面呢?这将有助于提高任何 Web 开发项目的生产力。考虑到这一点,我着手构建了一个支持 AJAX 且易于自定义的 jQuery 登录插件。
最基本地,登录界面总是包含两个文本框——一个用于用户名,一个用于密码,以及一个提交按钮。登录界面可以占据整个网页或部分网页,并使用 CSS 语言进行样式设计。本文描述了此 jQuery 插件的构建过程,并讨论了一些学习要点。我还构建了一个示例 Web 应用程序来演示此插件的用法。
Using the Code
首先,让我们设置示例 Web 应用程序,以便我们可以看到该插件的功能。解压缩源文件,我们应该会得到一个名为“jquery_ajaxlogin_demo”的文件夹和一个名为“testdb.sql”的 SQL 脚本。
将“testdb.sql”导入 MySQL 服务器,我们将会看到一个名为“testdb”的数据库,其中包含一个名为“user
”的表。我们可以为我们的数据库设置用户名和密码。
“jquery_ajaxlogin_demo”文件夹包含插件“jquery.ajaxlogin.js”以及其他文件。
在“jquery_ajaxlogin_demo”文件夹中,在文本编辑器中打开“login.php”文件,将 `mysqli_connect()` 的“username”和“password”更改为我们为“testdb
”数据库分配的那些。接下来,将“jquery_ajaxlogin_demo”文件夹移至 Apache 服务器的 webroot。
启动 Apache 和 MySQL 服务器,然后打开浏览器并输入“https:///jquery_ajaxlogin_demo/index.html”,我们将看到以下屏幕
在“Email”和“Password”框中分别输入“peterleow@somemail.com”和“password”,然后点击“Sign in”按钮登录。等待结果时,按钮将被替换为一个动画图标,如下图所示。
成功登录后,我们将被重定向到一个名为“welcome.php”的新页面。尝试使用任何其他无效的用户名和密码登录,并自行查看响应。
我们已经借助示例 Web 应用程序看到了插件的工作原理。现在,让我们看一下插件“jquery.ajaxlogin.js”本身。在文本编辑器中打开此文件以查看其内容。
/*
Title: JQuery Plugin for Ajax Login
Author : Peter Leow @ 11 Nov 2013
*/
(function($) {
$.fn.ajaxLogin = function(args){
if (args.length == 0 || args.action == undefined || args.success_redirect_page == undefined) {
alert ("Missing parameters!");
return
};
this.html('<div class="ajaxlogin_container"><form action=""
id="ajaxlogin_action"><header
id="ajaxlogin_header">Please Log in...</header>
<div><input type="text" placeholder="Username"
required id="ajaxlogin_username" /></div>
<div><input type="password" placeholder="Password"
required id="ajaxlogin_password" /></div>
<div id="progress"><input type="submit"
value="Log in" id="ajaxlogin_submit"
/></div></form></div>');
$("#ajaxlogin_action").attr("action", args.action);
success_redirect_page = args.success_redirect_page;
if (args.success_response != undefined) {
success_response = args.success_response;
} else {
success_response = "true";
};
if (args.error_msg != undefined) {
error_msg = args.error_msg;
} else {
error_msg = "Sign in unsuccessful!";
};
if (args.username_label != undefined) {
$("#ajaxlogin_username").attr("placeholder", args.username_label);
};
if (args.password_label != undefined) {
$("#ajaxlogin_password").attr("placeholder", args.password_label);
};
if (args.submit_label != undefined) {
$("#ajaxlogin_submit").attr("value", args.submit_label);
};
if (args.header_label != undefined) {
$("#ajaxlogin_header").html(args.header_label);
};
var progress_image_src = "";
if (args.progress_image_src != undefined) {
progress_image_src = args.progress_image_src;
};
$("#ajaxlogin_action").submit(function(){
var username=$("#ajaxlogin_username").val();
var password=$("#ajaxlogin_password").val();
var oldcontent=$("#progress").html();
$.ajax({
type: "POST",
url: "login.php",
data: "username="+username+"&password="+password,
success: function(response){
if(response == success_response)
{
window.location = success_redirect_page;
}
else
{
if (progress_image_src != ""){
$("#progress").html(oldcontent);
}
alert(error_msg);
}
},
beforeSend: function()
{
if (progress_image_src != ""){
$("#progress").html('<img src="'+
progress_image_src+
'" alt="Loading in progress..." id="ajaxlogin_progress_image" />');
}
}
});
return false;
});
return this; // make this plug-in chainable
};
}( jQuery ));
要使用此插件在网页上插入登录界面,例如我们示例 Web 应用程序中的“index.html”,首先将 jQuery 库“jquery.min.js”和插件“jquery.ajaxlogin.js”与“index.html”放在一起,然后将以下代码复制到“index.html”的 `head` 部分,并使用实际值更新相应的参数。总共有九个参数,每个参数都有不同的用途,但只有两个是必需的。
<script src="jquery.ajaxlogin.js"></script>
<script>
$(document).ready(function(){
// parameter is an associate array with 9 elements, only 2 are compulsory, order not important
$("id of div that will contains the login elements").ajaxLogin({
// compulsory
action: "name of server-side script to process your login",
// compulsory
success_redirect_page: "name of web page to re-direct to upon successful login",
// optional, default is "true"
success_response: "value returned from server to indicate successful login",
// optional, default is "Sign in unsuccessful!"
error_msg: "erro message for alert box upon failed login",
// optional, default is"Username"
username_label: "label for username textbox",
// optional, default is "Password"
password_label: "label for password textbox",
// optional, default is "Log in"
submit_label: "label for submit button",
// optional, default is "Please Log in..."
header_label: "label for login header",
// optional, default is no image
progress_image_src: "location of animated image"
});
});
</script>
以下示例显示了如何仅使用两个必需参数将插件包含在“index.html”页面中,它会生成随后的屏幕
<!DOCTYPE HTML>
<html>
<head>
<title>JQuery Ajax Login Plugin Demo</title>
<link href="style_01.css" rel="stylesheet" type="text/css">
<!-- include JQuery Library -->
<script src="jquery.min.js"></script>
<script src="jquery.ajaxlogin.js"></script>
<script>
$(document).ready(function(){
$(".container").ajaxLogin({
action: "login.php", // compulsory
success_redirect_page: "welcome.php", // compulsory
});
});
</script>
</head>
<body>
<div style="text-align: center;">
<h2>JQuery Ajax Login Plugin Demo</h2>
</div>
<div class="container"></div>
<div style="text-align: center;">
<p>Created by Peter Leow</p>
</div>
</body>
</html>
我们可以通过为插件的可选参数提供不同的值来定制登录界面的标签。本文中我们看到的第一个屏幕图像是由以下页面生成的,该页面使用了所有参数的插件
<!DOCTYPE HTML>
<html>
<head>
<title>JQuery Ajax Login Plugin Demo</title>
<link href="style_01.css" rel="stylesheet" type="text/css">
<!-- include JQuery Library -->
<script src="jquery.min.js"></script>
<script src="jquery.ajaxlogin.js"></script>
<script>
$(document).ready(function(){
$(".container").ajaxLogin({
action: "login.php", // compulsory
success_redirect_page: "welcome.php", // compulsory
success_response: "true",
// optional, default is "true", must match the return value
// from server-side script stated in action upon success
error_msg: "Sign in failed, try again.", // optional,
// default is "Sign in unsuccessful!"
username_label: "Email", // optional, default is"Username"
password_label: "Password", // optional, default is "Password"
submit_label: "Sign in", // optional, default is "Log in"
header_label: "Please Sign in...", // optional, default is "Please Log in..."
progress_image_src: "progress_image.gif" // optional
});
});
</script>
</head>
<body>
<div style="text-align: center;">
<h2>JQuery Ajax Login Plugin Demo</h2>
</div>
<div class="container"></div>
<div style="text-align: center;">
<p>Created by Peter Leow</p>
</div>
</body>
</html>
接下来,我们可以通过 CSS 自定义登录界面的外观。该插件为此目的公开了五个选择器。下面的 CSS 文件“style_01.css”提供了我们在本文开头看到的第一个屏幕的外观。
/* the container that holds the login elements */
.ajaxlogin_container {
margin-left:auto;
margin-right:auto;
border:2px solid #c3c3c3;
padding: 30px 30px;
background:#cccccc;
width: 300px;
border-radius:10px;
box-shadow: 8px 8px 8px #666666;
font-family:Arial,Helvetica,sans-serif;
}
/* the login form */
#ajaxlogin_action{
margin-left:auto;
margin-right:auto;
width:80%;
}
/* the username textbox and password textbox */
#ajaxlogin_username, #ajaxlogin_password{
width:80%;
margin-left: 23px;
border: 1px solid #656565;
-webkit-border-radius: 8px;
-moz-border-radius: 8px;
border-radius: 8px;
outline:0;
height:25px;
padding-left:10px;
padding-right:10px;
}
/* the submit button */
#ajaxlogin_submit{
margin-left: 160px;
height:: 22px
border-top: 1px solid #96d1f8;
background: #64c9d7;
background: -webkit-gradient(linear, left top, left bottom, from(#3e779d), to(#65a9d7));
background: -webkit-linear-gradient(top, #3e779d, #65a9d7);
background: -moz-linear-gradient(top, #3e779d, #65a9d7);
background: -ms-linear-gradient(top, #3e779d, #65a9d7);
background: -o-linear-gradient(top, #3e779d, #65a9d7);
padding: 5px 10px;
-webkit-border-radius: 8px;
-moz-border-radius: 8px;
border-radius: 8px;
-webkit-box-shadow: rgba(0,0,0,1) 0 1px 0;
-moz-box-shadow: rgba(0,0,0,1) 0 1px 0;
box-shadow: rgba(0,0,0,1) 0 1px 0;
text-shadow: rgba(0,0,0,.4) 0 1px 0;
color: white;
font-size: 14px;
font-family: Georgia, serif;
text-decoration: none;
vertical-align: middle;
}
#ajaxlogin_submit:hover {
border-top-color: #28597a;
background: #28597a;
color: #ccc;
}
#ajaxlogin_submit:active {
border-top-color: #1b435e;
background: #1b435e;
}
/* the progress image if any */
#ajaxlogin_progress_image{
margin-left: 160px;
width: 22px;
height:: 22px;
}
/* the title of the log in form */
#ajaxlogin_header{
margin-left: 23px;
}
作为比较,我提供了另一个 CSS 文件“style_02.css”,它将产生更简洁的外观,如下所示
关注点
我想分享以下学习要点
- jQuery 插件是一个自定义函数,它扩展了 jQuery 的原型对象,即“
jQuery.fn
”或“$.fn
”。通过扩展原型对象,我们可以使所有 jQuery 对象继承我们添加的任何函数。因此,要创建此插件,我们只需将函数“ajaxLogin
”添加到“jQuery.fn
”即可,它就可以像任何其他 jQuery 函数一样使用了。然后,我们可以以通常的 jQuery 方式调用该插件,即$(".element_id").ajaxLogin({...})
- 还有两个问题需要考虑,一个是如何使插件可链式调用,另一个是如何防止与其他也使用“
$
”的库发生冲突。第一个很简单,只需在插件函数末尾添加“return this
”即可完成。在“index.html”页面中的“ajaxLogin()
”之后添加一个 `animate()` 函数,如下所示,并在浏览器上进行测试以查看效果。$(document).ready(function(){ $(".container").ajaxLogin({ ... ... }).animate({ opacity:'0.5', }); });
- 为了解决第二个问题,我们需要将插件函数放在一个立即执行函数表达式 (IIFE) 中,并将函数“jQuery”和参数“
$
”传递给它。(function ($) { $.fn.ajaxLogin = function(args){ ... ... return this; // make this plug-in chainable }; }( jQuery));
- 最后但同样重要的是,在等待服务器响应时使用动画图像替换登录按钮。除了向用户显示他们的请求正在处理中,它还有一个更重要的功能,就是移除登录按钮,这样冲动的用户就不能不停地点击它。这比简单地禁用按钮更优雅。如果登录尝试失败,登录按钮将恢复,然后会弹出一个警告框通知用户。请查看“
$.ajax()"
中的代码,了解它是如何实现的。
我们已经到了本文的结尾。我希望本文能为我们的读者提供一个开发 jQuery 插件的良好开端。谢谢。
历史
- 第二版:2013 年 11 月 24 日,在源文件夹中插入了“testdb.sql”。这是我在第一版中的疏忽。我必须感谢 Member 10421332 的提醒。
- 第一版:2013 年 11 月 11 日