×

不用刷新,也可以登录,来学习下吧!

作者:jiang2017.06.14来源:Web前端之家浏览:12090评论:0
关键词:JQueryJS

用jquery无刷新登录的功能,这个现在很使用,直接上干货了。 首先先创建html的部分,直接用的表格。

HTML

<table> 
    <tr> 
        <td> 
        用户名: 
        </td> 
        <td> 
        <input type="text" id="username" /> 
        </td> 
    </tr> 
    <tr> 
        <td> 
        密码: 
        </td> 
        <td> 
        <input type="text" id="password" /> 
        </td> 
    </tr> 
    <tr> 
        <td> 
        验证码: 
        </td> 
        <td> 
        <input type="text" id="cord" /> 
        <img alt="点击更换验证码" title="看不清楚,请单击我!" id="checkcord" src="img.ashx" /> 
        </td> 
    </tr> 
    <tr> 
        <td> 
        <input type="button" onclick="login();" value="登录" /> 
        </td> 
        <td> 
        </td> 
    </tr> 
</table>

这里面包含的功能有:登录的验证,点击更换验证码。这个没有什么好说的。

JS

<script src="jquery-2.1.1.min.js" type="text/javascript"></script>
<script type="text/javascript"> 
//用jquery实现无刷新的登录验证 
function login() { 
    $.ajax({ 
        url: 'Login.ashx', //访问路径 
        data: 'username=' + $("#username").val() + "&password=" + $("#password").val() + "&cord=" + $("#cord").val(), //需要验证的参数 
        type: 'post', //传值的方式 
        error: function () {//访问失败时调用的函数 
        alert("链接服务器错误!"); 
        }, 
            success: function (msg) {//访问成功时调用的函数,这里的msg是Login.ashx返回的值 
            alert(msg); 
        } 
    }); 
} 
//验证码图片 
$(function () { 
    $("#username").focus(); 
    $("#checkcord").click(function () { 
        $("#checkcord").attr("src", "img.ashx?time=" + new Date()); 
    }); 
}) 
</script>

大概的核心代码就是这些了,当用户点击登录按钮时,触发login事件,用jquery向Login.ashx发出请求,在Login.ashx当中,仅仅只是验证用户名和密码是否匹配,验证码是否正确。Login.ashx是用C#语言写的,如果你们学习的是别的语言就将地址更换为别的就可以了。

img.ashx是生成验证码的程序,每点击一次图片都会重新访问img.ashx,所以图片是更换的,在生成图片的时候,会生成存储验证码的session,在Login.ashx当中,判断用户输入的值和session的值是否相同就可以了。在这里我只显示主要的源码了。代码如下:

context.Response.ContentType = "text/plain"; 
string username = context.Request.Form["username"]; 
string password = context.Request.Form["password"]; 
string cord = context.Request.Form["cord"]; 
if (context.Session["cord"] != null) 
{ 
if (context.Session["cord"].ToString() == cord) 
{ 
if (username == "admin" && password == "admin") 
{ 
    context.Response.Write("登录成功!"); 
} 
else 
{ 
    context.Response.Write("登录失败!用户名和密码错误!"); 
} 
} 
else 
{ 
    context.Response.Write("验证码错误!"); 
} 
}

这是判断登录的代码。

您的支持是我们创作的动力!
温馨提示:本文作者系 ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://jiangweishan.com/article/biji123.html

网友评论文明上网理性发言 已有0人参与

发表评论: