您的位置:首页 > 其它

手写Ajax程序实现异步刷新求和

2017-04-20 13:43 288 查看
WebForm.aspx.cs代码(如果手工编写Ajax应用程序,在后台的page_load中需要手工输出XML代码(response.write))

protected void Page_Load(object sender, EventArgs e)
{
if(Request.Params["op"]=="get")//只有传递过来的URL中op=get时才执行
{
Response.ContentType = "text/xml;charset=UTF-8";//文本为xml格式
Response.AddHeader("Cache-Control","no-Cache");
string t1 = Request.Params["TextBox1"];
string t2 = Request.Params["TextBox2"];
int s = int.Parse(t1) + int.Parse(t2);
Response.Write("<res>"+s.ToString()+"</res>");//输出xml格式数据
Response.End();
}
}


WebForm.aspx代码:

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script>
var xmlhttp;
if(window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();//其他浏览器
}
else if (window.ActiveXObject) {
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");//旧版IE
}
catch (e) { }
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");//新版IE
}
catch (e) { }
if (!xmlhttp) {
window.alert("不能创建XMLHttpRequest对象");
}
}
//发起Ajax请求后,一旦服务器响应请求就自动执行回调函数如下
xmlhttp.onreadystatechange = function () {
if(xmlhttp.readyState==4)//XMLHttpRequest对象的状态信息,4表示完成
{
if(xmlhttp.status==200)//服务器的询问请求状态,200表示已就绪
{
var xmlobj = xmlhttp.responseXML;//xml数据对象,即Page_Load中输出的内容
var t = xmlobj.getElementsByTagName("res")[0].firstChild.nodeValue;//获取带有指定标签名的对象的集合,以列表形式
//firstChild 属性返回被选节点的第一个子节点,<res></res>就是被选结点,标签中的内容就是子节点
alert(t);
}
else
{
alert(xmlhttp.status);
}
}
}
function ajax()
{
//发起Ajax请求
xmlhttp.open("GET", "WebForm.aspx?op=get&TextBox1=" + document.getElementById("TextBox1").value + "&TextBox2=" + document.getElementById("TextBox2").value, true);
xmlhttp.send(null);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
+<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<br />
<input id="Button1" type="button" value="求和" onclick="ajax()"/></div>
</form>
</body>
</html>

运行结果如下:



保持数1不变,只改变数2的值

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: