先建一个JS文件命名为Ajax.js

functionCreateXMLHttpRequest()//这里是构造XMLHttpRequest对象的方法
...{
varxmlHttpRequest=null;//这里是大家都常用的IE,firefox中取得XMLHttpRequest对象的方法
try
...{
xmlHttpRequest=newXMLHttpRequest();
}
catch(e)
...{
try
...{
xmlHttpRequest=newActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
...{
xmlHttp=newActiveXObject("Microsoft.XMLHTTP");
}
}
returnxmlHttpRequest;
}
functionAjaxSubmit(url,data,changeFunction)//url指定跳转页,data是要post的数据。changeFunction类似于函数指针
...{
varxmlHttpResquest=CreateXMLHttpRequest();
xmlHttpResquest.open("post",url,true);
xmlHttpResquest.setRequestHeader("content-length",data.length);
xmlHttpResquest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlHttpResquest.send(data);
xmlHttpResquest.onreadystatechange=function()
...{
if(xmlHttpResquest.readyState==4)
...{
try
...{
if(xmlHttpResquest.status==200)
...{
alert(xmlHttpResquest.responseText);
changeFunction(xmlHttpResquest.responseText);//这里可以调用想要的函数
}
}
catch(e)
...{
alert("over");
}
}
}
}
比如我有一个页面叫Start.html或者Start.aspx
<head>
<title>UntitledPage</title>
<scripttype="text/javascript"src="Ajax.js"></script>
</head>
<body>
<scriptlanguage="javascript"type="text/javascript">
AjaxSubmit("Ajax.aspx","nodesInfoTxt=hh",InitForAjax);
//Ajax.aspx是接受数据的页面,InitForAjax是本页面接受到回发数据后要执行的函数。其他的为数据。
functionInitForAjax(str)
...{
alert(str);
}
</script>
</body>
一般.net生成的aspx页面是这样写的

<%...@PageLanguage="C#"AutoEventWireup="true"CodeFile="Ajax.aspx.cs"Inherits="Ajax"%>
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml">
<headrunat="server">
</head>
<body>
<formid="form1"runat="server">
<div>
</div>
</form>
</body>

</html>
下面为了回传数据仅仅是数据而不是连同整个页面一起发送过来。
在Ajax.aspx页面这样这样写(这一句就足够了)
<%@PageLanguage="C#"AutoEventWireup="true"CodeFile="Ajax.aspx.cs"Inherits="Ajax"%>
然后在它的后置类也就是Ajax.aspx.cs中这样写:
//前面省略一些代码生成的东西
protectedvoidPage_Load(objectsender,EventArgse)
...{
if(Request.Form["nodesInfoTxt"]!=null)
stringnodes=Request.Form["nodesInfoTxt"].ToString();
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.ContentType = "text/xml";
Response.ContentType = "text/xml";
Response.write("bye");
}
}你在本函数结束处设一个断点,是否nodes就已经被赋值了呢?然后继续执行你的页面就会跳出一个bye的提示框。这就是Ajax异步传输。
本文介绍了一种使用JavaScript实现Ajax异步传输的方法。通过创建XMLHttpRequest对象并定义回调函数,可以实现在不重新加载整个页面的情况下,仅更新部分数据。
677

被折叠的 条评论
为什么被折叠?



