前端代碼,获取input中的账号和密码,用get方式传递到后端ashx页面判断
前端js代码
$('#login').click(function (event) {
var xhr;
var user = document.getElementById("user").value;
var passwd = document.getElementById("passwd").value;
if (window.XMLHttpRequest) {//ie8及以上版本、ff、chrom
xhr = new XMLHttpRequest();
}
else {//ie6及以下版本
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
//设定请求对象和后台哪个页面进行交互
xhr.open("GET", "Handler1.ashx?user=" + user + "&passwd=" + passwd, true);
//发送请求
xhr.send();
//后台返回数据后,会调用此方法(回调函数)
xhr.onreadystatechange = function (data) {
if (xhr.readyState == 4) {
document.getElementById("myDiv").innerHTML = xhr.responseText;
}
}
if (xhr.responseText = "true") {
alert("success");
location.href = "HTMLPage1.htm";
}
});
ashx一般处理程式进行判断 连接MySQL数据库,带人账号密码去检查是否存在,存在写入true,不存在写入false
public class Handler1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string user=context.Request.QueryString["user"];
string passwd=context.Request.QueryString["passwd"];
string sql = "select * from users where username= '" + user + "' and passwd= '" + passwd + "';";
context.Response.Write(LinkMysql(sql).ToString());
}
public bool LinkMysql(string sql)
{
String connetStr = "server=127.0.0.1;port=3306;user=root;password=root;database=spdb1";
MySqlConnection conn = new MySqlConnection(connetStr);
try
{
conn.Open();
MySqlCommand cmd = new MySqlCommand(sql, conn);
MySqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
return true;
}
else {
return false;
}
}
catch (MySqlException ex)
{
return false;
}
finally
{
conn.Close();
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}