ajax之简单调用

来源:互联网 发布:unity3d 克隆对象 编辑:程序博客网 时间:2024/05/01 05:43

 

 

(一)前台

<!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() {
            var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); //创建XMLHTTP对象,相当于WebClient

            if (!xmlhttp) {
                alert("创建xmlhttp对象异常!");
                return false;
            }
            xmlhttp.open("POST", "/01ajax/GetDate.ashx?id=33&ts=" + new Date(), false);
            //准备向服务器的GetDate1.ashx发出Post请求,XMLHTTP默认(也推荐)不是同步请求的,
            //也就是open方法并不像WebClient的DownloadString那样把服务器返回的数据拿到才返回,
            //是异步的,无法直接拿到send的返回值,因此需要监听onreadystatechange事件


            xmlhttp.onreadystatechange = function () {
                if (xmlhttp.readyState == 4) { //服务器完成(可能成功也可能失败)
                    if (xmlhttp.status == 200) { //如果状态为200则是成功
                        //alert(xmlhttp.responseText);
                        document.getElementById("Text1").value = xmlhttp.responseText;
                        //responseText属性为服务器返回的文本,把服务器返回的文本赋值给Id为Text1的文本框的value属性
                    }
                    else {
                        alert("AJAX服务器返回错误!");
                    }
                }
            }
    
                xmlhttp.send(); //这时才开始返回请求
      }
           
    </script>


</head>
<body>

<input type="text" id="Text1" />
<input type="button" value="使用ajax获得服务器时间" onclick="btnClick()" />

</body>
</html>

 

(二)后台

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace _13ajax._01ajax入门
{
    /// <summary>
    /// GetDate 的摘要说明
    /// </summary>
    public class GetDate : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            //context.Response.Write("Hello World");

            //context.Response.Write(DateTime.Now.ToString());

            string name = context.Request["name"].ToString();//得到前台使用ajax方式传过来的name字段

            context.Response.Write(name);//打印出name字段的值

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}