在网上找了几个帖子,但是由于水平有限,折腾了一会才实现了一个小程序。理论理解之后,加之一个实际Demo,对于新手理解ajax是很容易的。
我将具体的代码都贴上,方便和我一样初次学习的人理解。
操作步骤如下:
首先是请求页面的前台代码:
<!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 type="text/javascript"> function createXHR() { var xhr = null; try { // Firefox, Opera 8.0+, Safari,IE7+ xhr = new XMLHttpRequest(); } catch (e) { // Internet Explorer try { xhr = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { xhr = null; } } } return xhr; } function setContainer(text) { document.getElementById("container").value = text; } function testajax() { var xhr = createXHR(); xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) { setContainer(‘Original Ajax: ‘ + xhr.responseText); //alert(xhr.status); } } xhr.open(‘get‘, ‘WebForm2.aspx?action=getTime‘, true); xhr.send(); } </script> </head> <body> <input id="Button1" type="button" value="测试ajax" onclick="testajax()" /> <input id="container" type="text" /> </body> </html>
然后是被请求页面的后台数据处理
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Xml.Linq; namespace _02 { public partial class WebForm2 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string action = Request.QueryString["action"].ToString(); if (Request.QueryString["action"]!=null) { switch (action) { case "getTime": Response.Write(GetTime()); break; case "getDate": Response.Write(GetDate()); break ; } Response.End(); } } private string GetTime() { return DateTime.Now.ToShortTimeString(); } private string GetDate() { return DateTime.Now.ToShortDateString(); } } }
时间: 2024-10-06 16:34:45