<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
function btnClick() {
// //建立一個相容三大主流浏覽器的xmlhttpRequest對象
// var xmlhttp = false;
// try{
// xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");//ie msxml3.0+
// }
// catch(e){
// try{
// xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");//ie msxml2.6
// }
// catch(e2){
// xmlhttp = false;
// if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {//Firefox,Opera 8.0,Safari
// xmlhttp = new XMLHttpRequest();
// return xmlhttp;
// }
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); //建立一個XMLHTTP對象
if (!xmlhttp) {
alert("建立xmlhttp對象異常!");
return false;
}
xmlhttp.open("POST", "GetDate1.ashx?id="+encodeURI("中國")+"&ts" + new Date(), true); //準備向伺服器的GetDate1.ashx發送請求
//XMLHTTP預設(也推薦)不是同步請求的,也就是open方法并不像webClient的DownloadString那樣把伺服器傳回的資料拿到才傳回,是異步的,是以需要監聽onreadystatechange事件
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {//如果狀态是200表示成功
document.getElementById("Text1").value = xmlhttp.responseText;//responseText屬性為伺服器傳回的資料
}
else {
alert("Ajax伺服器傳回錯誤!");
}
xmlhttp.send();
}
</script>
</head>
<body>
<input id="Text1" type="text"/>
<input type="button" id="Button1" value="button" onclick="btnClick()"/>
</body>
</html>
ashx:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace AJax
{
/// <summary>
/// GetDate1 的摘要說明
/// </summary>
public class GetDate1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string id = context.Request["id"];//擷取到用戶端的變量
string ts = context.Request["ts"];
ts = "hello";
context.Response.Write(DateTime.Now.ToString() + "---" + id+"--"+ts); //傳回給用戶端資料
public bool IsReusable
get
{
}
}
本文轉自蓬萊仙羽51CTO部落格,原文連結:http://blog.51cto.com/dingxiaowei/1366593,如需轉載請自行聯系原作者