以下内容是看了杨中科(传智播客)老师的.net视频及牛腩老师的新闻发布系统视频相关Ajax章节所做大概记录,初学理解能力有限,因此笔记可能有误

一、用JS原始代码实现Ajax(不用任何Ajax框架)

1、新建AjaxText.html

    -点击Button1按钮获取服务器时间并显示到Text1文本框中

<!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>用JS原始代码实现Ajax,面试经常会要求写</title>
    </head>
<body>
获取服务器时间:<br/>
    <input id="Text1" type="text" />
    <input id="Button1" type="button" value="获取" onclick="btnClick()" />
</body>
</html>

 2、添加JS代码,该JS用于实现Ajax

     -这里要注意,如果把JS或JQuery写在单独的JS文件中,ashx页面url要相对于html或aspx页面,而不是相对于js页面

<script type="text/javascript">
        function btnClick() {
            var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); //创建XMLHTTP对象,相当于WebClient(注意,这是微软IE下的方法,在其他浏览器是不支持的)
            if (!xmlhttp) {
                alert("创建xmlhttp对象异常!");
                return false;
            }
            //准备向服务器的GetDate.ashx页面发出POST请求,并传递参数id,&ts=new Date().getTime()为预防页面有缓存
        xmlhttp.open("POST", "GetDate.ashx?id="+encodeURI("中国")+" &ts="+new Date().getTime(), false); 
            //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>


3、新建一般处理程序页面GetDate.ashx

public void ProcessRequest(HttpContext context)
{
     context.Response.ContentType = "text/plain";
     string id = context.Request["id"];
     context.Response.Write(DateTime.Now.ToString()+"--页面传过来的参数id="+id);//获取服务器时间,★通过context.Response.Write()返回数据
}

 注:ashx通过context.Response.Write()来返回数据

 二、用JQuery实现Ajax(一般都是用JQuery来实现Ajax,比较方便)

   引出JQuery.js文件,并将第一步中的Js代码改为JQuery代码

 function btnClick() {
     $.post("GetDate.ashx", { "id": "中国"}, function(data, status) {
          if (status = "success") {   // 第二个参数status为服务器返回状态码,success表示返回成功
              $("#Text1").val(data); // 第一个参数data为服务器返回的内容
          }
          else {   //如果返回失败
              alert("AJAX错误!");
          }
      });
  }

JQuery中提供了简化ajax使用的方法。$.ajax()函数是JQuery中提供的ajax访问函数,一般不直接调用$.ajax()函数,

$.post()是对$.ajax()的post方式提交ajax查询的封装,$.get()对$.ajax()的get方式提交ajax查询的封装。推荐用post方式,因为post方式没有缓存的问题。

如果需要在出错时执行函数,请使用 $.ajax。

$.post(url,[data],[callback],[type]):第234参数为可选

url:为发送请求的地址,如上面的GetDate.ashx(注意,这里的ashx页面路径,是相对于页面的路径,而不是相对于JS文件的路径)

data:待发送的key/value参数,为字典数组,如{"id":idText , "name":nameText},也可把url写成"GetDate.ashx?id="+idText+"&name="+nameText形式,而省略改参数,该post方法会自动对传进来的中文参数进行编码;

(★注意:如果用$.get()则必须解决缓存问题,可加参数"t":new Date().getTime();还必须考虑编码问题,如果传入的参数value是中文,存到数据库会有乱码,因此必须进行二次转码,如"name":encodeURI(encodeURI(nameText)),然后在ashx中再对该参数值进行解码context.Server.UrlDecode(context.request["name"],因此推荐使用$.post())  

calback:发送成功时回调函数,如上面的function(data,status){},回调函数中data(可省略)为服务器返回的数据,status(可省略)为服务器返回状态码status = "success"表示返回成功

三、上面方法回传的数据都是单字符串,可用Json实现传数组

1、新建JsonTest.html文件,在html文件中加入一下JQuery代码

<script type="text/javascript">
        $(function() {
            $.post("JsonTest.ashx", function(data, status) {
                //alert(data);//弹出字典数组行式的字符串{"Name":"tom","Age":30}
                var person = $.parseJSON(data);//反序列,直接得到一个字典数组
            alert(person.Name);//相当于person["Name"]
            });
        });
</script>

2、新建一般处理程序页面JsonTest.ashx 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization; //引入该命名空间

namespace Ajax
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class JsonTest: IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            //JavaScriptSerializer为启用 AFAX 的应用程序提供序列化和反序列化功能。
        JavaScriptSerializer jss = new JavaScriptSerializer();
            //Serialize():当在派生类中重写时,生成名称/值对的字典数组。
        string json = jss.Serialize(new Person() { Name = "tom", Age = 30 });
            context.Response.Write(json);//返回一个字典数组形式的字符串:{"Name":"tom","Age":30}
        }

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

    public class Person 
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
}
posted on 2010-12-30 12:03  墟零  阅读(950)  评论(4编辑  收藏  举报