Ajax+jQuery实现LightBox与服务器通信
2010-09-14 13:42:23 来源:WEB开发网这里的变量xmlHttp是全局的,下面还会再用到。因为IE和其他标准浏览器的XMLHttpRequest对象不一样,所以我用了两个条件判断来兼容IE。
创建了XMLHttpRequest对象以后就要用它向服务端发送请求了
1function Login()
2{
3 CreateXMLHttpRequest();
4
5 var strUserName=$("#tbUserName").val();
6 var strPassword=$("#tbPassword").val();
7 var url="/test/Ajax.aspx?userName="+strUserName+"&password="+strPassword;
8 xmlHttp.open("GET",url,true);
9 xmlHttp.onreadystatechange=CallBack;
10 xmlHttp.send(null);
11}
12
首先获取表单上的值,并根据获得的值构造请求用的url。再用get方法发送请求。这些似乎都是Ajax的标准代码了。发送了请求我们再看服务器要怎么响应了。
1 protected void Page_Load(object sender, EventArgs e)
2 {
3 //string strAction = Request.QueryString["action"];
4 //switch (strAction)
5 //{
6 // case login:
7 // {
8 string strUserName = Request.QueryString["userName"];
9 string strPassword = Request.QueryString["password"];
10 LoginCallBack(strUserName,strPassword);
11 //break;
12 // }
13 //}
14
15
16 }
17
18 protected void LoginCallBack(string strUserName,string strPassword)
19 {
20 string strCommandText = "SELECT * FROM admin WHERE name='" + strUserName + "' AND password='" + strPassword + "'";
21 SqlConnection myConnection = new SqlConnection(strCONNECTION_STRING);
22 SqlCommand myCommand = new SqlCommand(strCommandText, myConnection);
23 SqlDataReader myReader;
24 myConnection.Open();
25 myReader = myCommand.ExecuteReader();
26 if (myReader.Read())
27 {
28 Session["UserName"] = myReader.GetString(1);
29 Session["Password"] = myReader.GetString(2);
30 Response.ContentType = "text/plain";
31 Response.AppendHeader("Cache-Control", "no-cache");
32 Response.AppendHeader("Pragma", "no-cache");
33 Response.Write("欢迎:" + Session["UserName"]);
34 Response.End();
35 }
36 else
37 {
38 Response.Write("登录失败");
39 }
40 }
41}
42
更多精彩
赞助商链接