Ajax基础:2.原理示例
1.准备一般处理程序ashx,当请求时返回当前服务器时间
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
context.Response.Write(DateTime.Now.ToString());
}
2.编写javascript脚本,当然ActiveXObject(“Micsrosoft.XMLTTP”)只能支持IE
<script type="text/javascript" language="javascript">
function btnc() {
//创建xmlhttp对象
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
if (!xmlhttp) {
alert("创建xmlhttp对象异常")
return false;
}
xmlhttp.open("POST", "GetDate.ashx?ts=" + new Date(), false);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
//状态吗是200表示成功
if (xmlhttp.status == 200)
{
document.getElementById("txtTime").value = xmlhttp.responseText;
} else {
alert("返回数据错误");
}}
}
//发送请求
xmlhttp.send();
}
</script>
3.Jquery方式,做了很好的封装,使用起来很方便
$.post("GetDate.ashx", function (data, texStatus) {
$("#txtTime").val(data+texStatus);
});
$.post("GetDate.ashx",{"key":zhi;"id":1} function (data, texStatus)
4.示例:输入账号查出密码来
1)处理程序,取出传递来的参数name,查出数据,判断是否查到了相应数据
string name=context.Request["name"]; Admin data=AdminManager.getadminbyName(name); if (data.Id<=0) { context.Response.Write("none|0"); } else { context.Response.Write("ok|"+data.Pwd); }
2)编写jquery代码
<script type="text/javascript"> $(function () { $("#txtName").blur(function () { var name = $("#txtName").val(); $.post("GetPwd.ashx", { "name": name }, function (data, status) { if (status == "success") { var arrs = data.split("|"); if (arrs[0] == "ok") { $("#txtPwd").val(arrs[1]); } else if (arrs[0] == "none") { alert("mei you"); } else { alert("cuo wu"); } } else { alert("ajax cuo wu"); } }); }); }); </script>
浙公网安备 33010602011771号