首先引用 两个js 文件
1 <script src="js/jquery-1.7.1.js" type="text/javascript"></script> 2 <script src="js/Common.js" type="text/javascript"></script>
html 代码:
1 <body> 2 <div> 3 <input id="txtName" type="text" name="txtName" value="" /><br /> 4 <input id="txtPwd" type="password" name="txtPwd" value="" /><br /> 5 <input type="button" id="btnLogin" name="btnLogin" value="登陆" /> 6 <input type="hidden" name="name" value="3" /> 7 <span id="span"></span> 8 </div> 9 </body>
普通的js ajax 效果代码:
window.onload = function () {document.getElementById('btnLogin').onclick = function () {var name = document.getElementById('txtName').value;var pwd = document.getElementById('txtPwd').value;var xhr = createXhr();//xhr.open("post", "FirstAjax.ashx", true);xhr.open("post", "Login.aspx", true);xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");xhr.onreadystatechange = function () {if (xhr.readyState == 4) {if (xhr.status == 200) {var result = xhr.responseText;//alert(xhr.responseText);var json = eval("(" + result + ")");if (json.data == "1") {//alert("登陆成功!");document.getElementById('span').innerHTML = '登陆成功';window.location = "User.aspx";} else {document.getElementById('span').innerHTML = '登陆失败';}}}}xhr.send("Name=" + name + "&pass=" + pwd);}}
jquery 的ajax 实现方法:
1 $(document).ready(function () { 2 3 $("#btnLogin").click(function () { 4 $.ajax({ 5 type: "POST", 6 url: "Login.aspx", 7 dataType: "html", 8 data: { 9 name: $("#txtName").val(), 10 pass: $("#txtPwd").val() 11 }, 12 success: function (data) { 13 //将返回的json数据 转换一下 14 var obj = eval("(" + data + ")"); 15 //alert(obj.data); 16 if (obj.data == "1") { 17 //alert("登陆成功"); 18 $("#span").text("登陆成功!"); 19 //document.getElementById('span').innerHTML = '登陆成功'; 20 } 21 else { 22 $("#span").innerHTMl = '登陆失败!'; 23 } 24 }, 25 error: function () { 26 alert("出错了"); 27 } 28 }); 29 }); 30 });
后台的方法处理:
1 protected void Page_Load(object sender, EventArgs e) 2 { 3 if (!string.IsNullOrEmpty(Request.Form["name"])) 4 { 5 string UserName = Request.Form["name"]; 6 string UserPwd = Request.Form["pass"]; 7 if (UserName == "123" && UserPwd == "123") 8 { 9 Response.Write("{'data':'1'}"); 10 } 11 else 12 { 13 Response.Write("{'data':'2'}"); 14 } 15 Response.End(); 16 } 17 }