ajax_简单demo。页面存在textbox1和button1,点击按钮,返回服务器的时间,填写在textbox1中。无刷新整个页面。

贴上示例代码,ie中有效(搜狗没效果),其余未测。

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
function btnclick() {
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); //创建xmlhttp对象
if (!xmlhttp) {
alert("创建xmlhttp对象失败!");
}
xmlhttp.open("POST", "GetDate.ashx?ts" + new Date(), false);
xmlhttp.onreadystatechange = function () {

if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {

alert(xmlhttp.responseText);
document.getElementById("Text1").value = xmlhttp.responseText;
}
else {
alert("ajax服务器返回错误");
}

}
}
xmlhttp.send();
}
</script>
</head>
<body>
<input id="Text1" type="text" />
<input id="Button1" type="button" value="button" onclick="btnclick()"/>
</body>
</html>

其中GetDate.ashx页面只是返回服务器时间,无他用。代码如下:

public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
context.Response.Write(DateTime.Now.ToString());
}

public bool IsReusable {
get {
return false;
}
}

原文地址:https://www.cnblogs.com/fanshaomin/p/3841957.html