Get:
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> <script type="text/javascript"> window.onload = function () { document.getElementById("btnGet").onclick = function () { //第一步,创建XMLHttpRequest对象 var xhr = null; if (XMLHttpRequest) { xhr = new XMLHttpRequest(); } else { xhr = new ActiveXObject("Microsoft.XMLHttp"); } //第二部,设置异步回调函数。 xhr.onreadystatechange = function () { //xhr对象状态,0=已创建XMLHttpRequest对象,1=open,2=send,3=onready等待响应,4=成功。 if (xhr.readyState == 4) { //status 响应状态 if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) { document.getElementById("div1").innerHTML = xhr.responseText; //xhr.responseText 响应体 } } } //第三步,打开对象,设置请求方式和访问路径 xhr.open("Get", "GetTime.ashx?id=17&name=" + window.encodeURIComponent("张三"), true); //第四步,send() xhr.send(null); }; }; </script> </head> <body> <div id="div1"></div> <input type="button" value="无刷新异步获取" id="btnGet" /> </body> </html>
Post:
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> <script type="text/javascript"> window.onload = function () { document.getElementById("btn").onclick = function () { var xhr = null; if (XMLHttpRequest) { xhr = new XMLHttpRequest(); } else { xhr = new ActiveXObject("Microsoft.XMLHttp"); } xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) { document.getElementById("div1").innerHTML = xhr.responseText + "<hr />"; //获取响应报文头信息 var date = xhr.getResponseHeader("Date"); document.getElementById("div2").innerHTML = date + "<hr />"; //获取所有响应报文头信息 var all = xhr.getAllResponseHeaders(); document.getElementById("div3").innerHTML = all + "<hr />"; } } //通过Post方式请求 xhr.open("Post", "GetTime.ashx", true); //需要添加请求报文头,Content-Type. xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); //通过键值对的方式传值。 var name = document.getElementById("name").value; xhr.send("id=18&name=" + name); }; }; </script> </head> <body> <div id="div1"></div> <div id="div2"></div> <div id="div3"></div> <input type="text" id="name" value="李四" /> <input type="button" value="提交" id="btn" /> </body> </html>
GetTime.ashx:
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Web; namespace MyPerson.UI.Ajax { /// <summary> /// GetTime 的摘要说明 /// </summary> public class GetTime : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; //Thread.Sleep(1000); string id = context.Request["id"]; string name = context.Request["name"]; context.Response.Write(DateTime.Now.ToString() + "<br/>编号:" + id + "<br/>姓名:" + name); } public bool IsReusable { get { return false; } } } }