您的位置:首页 > 编程语言

Ajax手写代码实现-用户验证

2011-03-20 14:04 288 查看
首先我们创建一个html页面:Login.html,里面编写相应的js函数

<script type="text/javascript">
var xmlhttp;
//根据不同的浏览器,创建xmlHttpRequest对象
function createXmlHttpRequest() {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}

//提交请求
function doAjax() {
createXmlHttpRequest(); //创建xmlHttpRequest对象
//用户名和密码
var name = document.getElementById("txtName").value;
var pwd = document.getElementById("txtPwd").value;

//请求路径
var url = "Check.aspx?name=" + name + "&pwd=" + pwd + "";
if (xmlhttp != null) {
//true表示异步,若设置为false,在Firefox中不会执行
xmlhttp.open("post", url, true);
//指定回调函数
xmlhttp.onreadystatechange = processRequest;
xmlhttp.send(); //发送请求
}
}

function processRequest() {
//当请求完成4且服务器响应正常200
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
if (xmlhttp.responseText == "ok") {
alert('XMLHttpRequest对象读取响应结束!');
window.location = 'Main.htm';
}
else
alert('用户名或密码错误,请重新输入!');
}
}
</script>

在该页面<input type="button" value="登录" onclick="doAjax()" />调用;

在aspx页面Check.aspx的Load事件中调用如下方法:

private void CheckUser()
{
if (Request.QueryString["name"] != null
&& Request.QueryString["pwd"] != null)
{
string name = Request.QueryString["name"];
string pwd = Request.QueryString["pwd"];
int rows = UserManager.CheckUser(name, pwd);//调用业务逻辑层的方法验证用户和密码
if (rows > 0)
{
Response.Write("ok");
}
else
{
Response.Write("no");
}
}
}

这样就可以实现无刷新验证了。因为时间关系,暂时写到这里,希望能通过这个简单的案例,弄清楚Ajax手写代码的实现思路。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: