AjAx 页面传值 从入门到精通(含javascript ,AjAx,Json) 原文版 第一节

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

1、新建AjaxText.html

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

01 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
02 <html xmlns="http://www.w3.org/1999/xhtml" >
03 <head>
04     <title>用JS原始代码实现Ajax,面试经常会要求写</title>
05     </head>
06 <body>
07 获取服务器时间:<br/>
08     <input id="Text1" type="text" />
09     <input id="Button1" type="button" value="获取" onclick="btnClick()" />
10 </body>
11 </html>

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

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

01 <script type="text/javascript">
02         function btnClick() {
03             var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); //创建XMLHTTP对象,相当于WebClient(注意,这是微软IE下的方法,在其他浏览器是不支持的)
04             if (!xmlhttp) {
05                 alert("创建xmlhttp对象异常!");
06                 return false;
07             }
08             //准备向服务器的GetDate.ashx页面发出POST请求,并传递参数id,&ts=new Date().getTime()为预防页面有缓存
09         xmlhttp.open("POST", "GetDate.ashx?id="+encodeURI("中国")+" &ts="+new Date().getTime(), false); 
10             //XMLHTTP默认(也推荐)不是同步请求的,也就是open方法并不像WebClient的DownLoadString那样把服务器返回数据拿到才返回,是异步的,因此需要监听onreadystatechange事件
11         xmlhttp.onreadystatechange = function() {
12                 if (xmlhttp.readyState == 4) {  //服务器请求完成
13                     if (xmlhttp.status == 200) {  //如果状态码为200,则是请求成功
14                         document.getElementById("Text1").value = xmlhttp.responseText; //★responseText属性为服务器返回的文本
15                     }
16                     else {
17                         alert("AJAX服务器返回错误!");
18                     }
19                 }
20             }
21             xmlhttp.send();//这时才开始发送请求        
22      }
23       
24 </script>


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

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

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

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

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

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

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代码

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

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

01 using System;
02 using System.Collections.Generic;
03 using System.Linq;
04 using System.Web;
05 using System.Web.Services;
06 using System.Web.Script.Serialization; //引入该命名空间
07   
08 namespace Ajax
09 {
10     [WebService(Namespace = "http://tempuri.org/")]
11     [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
12     public class JsonTest: IHttpHandler
13     {
14         public void ProcessRequest(HttpContext context)
15         {
16             context.Response.ContentType = "text/plain";
17             //JavaScriptSerializer为启用 AFAX 的应用程序提供序列化和反序列化功能。
18         JavaScriptSerializer jss = new JavaScriptSerializer();
19             //Serialize():当在派生类中重写时,生成名称/值对的字典数组。
20         string json = jss.Serialize(new Person() { Name = "tom", Age = 30 });
21             context.Response.Write(json);//返回一个字典数组形式的字符串:{"Name":"tom","Age":30}
22         }
23   
24         public bool IsReusable
25         {
26             get
27             {
28                 return false;
29             }
30         }
31     }
32   
33     public class Person 
34     {
35         public string Name { get; set; }
36         public int Age { get; set; }
37     }
38
posted @ 2012-03-13 14:17  Star★  阅读(575)  评论(0编辑  收藏  举报