淘先锋技术网

首页 1 2 3 4 5 6 7

今天又从老王的博客学到了点东西,Form形式的HTTP Basic Authentication
一般来说用户登录验证大都用的SESSION来实现,但按老王的说法,这种方式不符合REST风格,更破坏了HTTP的无状态特性,从而对可扩展性造成障碍(以本人目前的水平还不能深入理解,囧)。

来是来个Demo看看吧

这是前端html页面


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<html>
<head>
<title>login</title>
<script>
function login() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
 
xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost/test.php", false, username, password);
xhr.send(null);
 
return xhr.status == 200;
}
</script>
</head>
<body>
<form action="http://localhost/test.php" method="post" onsubmit="return login();">
<label for="username">username:</label>
<input type="text" id="username" name="username">
 
<label for="password">password:</label>
<input type="password" id="password" name="password">
 
<input type="submit" value="submit">
</form>
</body>
</html>

这是要访问的后端PHP页面


使用帐号linvo密码123才可登录成功,数据被保存在$_SERVER中。
这段看ajax习惯了,看到XMLHttpRequest总想到异步传输,可是这里的open参数用的是false,同时用到了服务器验证信息的两个参数。

这里是XMLHttpRequest中open方法的详细参数:
oXMLHttpRequest.open(bstrMethod, bstrUrl, varAsync, bstrUser, bstrPassword);

bstrMethod
http方法,例如:POST、GET、PUT及PROPFIND。大小写不敏感。

bstrUrl
请求的URL地址,可以为绝对地址也可以为相对地址。

varAsync[可选]
布尔型,指定此请求是否为异步方式,默认为true。如果为真,当状态改变时会调用onreadystatechange属性指定的回调函数。

bstrUser[可选]
如果服务器需要验证,此处指定用户名,如果未指定,当服务器需要验证时,会弹出验证窗口。

bstrPassword[可选]
验证信息中的密码部分,如果用户名为空,则此值将被忽略。