简单的Ajax实例

由于刚刚接触Ajax,所以在网上搜了一下如何实现简单的Ajax,在此写下来,也方便自己以后学习

什么是Ajax?

通过在后台与服务器进行少量的数据交换,Ajax可以使网页实现异步更新,这意味着可以在不重新加载整个网页的情况下,对网页的某个部分进行更新。

在2005年,Google通过其Google Suggest使Ajax变得流行起来。

XMLHttpRequest是Ajax的基础。

创建XMLHttpRequest对象

var xmlHttp=new XMLHttpRequest();

老版本的IE5、IE6使用Active对象:var xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");

利用GET方法的实例如下:

静态网页Ajax.html

 1 <html>
 2     <head>
 3         <title>Ajax</title>
 4         <script type="text/javascript">
 5             function loadXMLDoc()
 6             {
 7                 var xmlHttp;
 8                 if(window.XMLHttpRequest)
 9                 { // code for IE7+
10                     xmlHttp = new XMLHttpRequest();
11                 }
12                 else
13                 { // code for IE5/IE6
14                     xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
15                 }
16                 
17                 xmlHttp.onreadystatechange=function()
18                 {
19                     if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
20                     {
21                         document.getElementById("myDiv").innerHTML=xmlHttp.responseText;
22                     }
23                 }
24 
25                 // get
26                 xmlHttp.open("GET", "Ajax.aspx", true);
27                 xmlHttp.send();
28             }
29         </script>
30     </head>
31     <body>
32         <h3>ajax</h3>
33         <button type="button" onclick="loadXMLDoc()">请求数据</button>
34         <div id="myDiv"></div>
35     </body>
36 </html>

动态网页Ajax.aspx的后台代码

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.UI;
 6 using System.Web.UI.WebControls;
 7 
 8 public partial class Ajax : System.Web.UI.Page
 9 {
10     protected void Page_Load(object sender, EventArgs e)
11     {
12         Response.Clear();
13         Response.Write(DateTime.Now.ToString("D"));
14         Response.End();
15     }
16 }

在此后台代码中只是向请求页面返回了一个当前时间,运行第一个静态页面的结果如下:

原文地址:https://www.cnblogs.com/lit10050528/p/3541413.html