zoukankan      html  css  js  c++  java
  • 封装AJax实现JSON前台与后台交互

    实践技术点:1、AJax自定义封装

          2、后台序列化与反序列化JSON

          3、客户端解析JSON字符串,处理DOM

    实现代码如下:

     1、JS脚本代码:

                    1 /***

      2 NOTE:AJAX处理JS
      3 TIME:2015-5-18 11:02:51
      4 AUTHOR:宋梦澜
      5 
      6 ***/
      7 
      8 var AJax = function (handleUrl) {
      9     this.Url = handleUrl ? handleUrl : "";
     10     this.xmlHttpRequest = null;
     11 
     14     this.CallFunc = null; //回调函数
     15     this.DataContent = null; //数据内容
     16 };
     17 
     18 AJax.prototype.CheckUrl = function () {
     19     var bo = false;
     20     //if (this.Url.indexOf('.') > 0) 
     21     if (this.Url.lastIndexOf('.') > 0) {
     22         bo = true;
     23     }
     24     else {
     25         bo = false;
     26     }
     27     return bo;
     28 };
     29 
     30 AJax.prototype.Init = function () {
     31     //判断浏览器是否支持异步对象
     32     if (window.XMLHttpRequest) {
     33         this.xmlHttpRequest = new XMLHttpRequest();
     34     }
     35     else if (window.ActiveXObject) {
     36         try {
     37             this.xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
     38         } catch (e) {
     39             this.xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
     40             if (console && console.log) {
     41                 console.log("无法创建异步请求对象!");
     42             }
     43         }
     44     }
     45 };
     46 
     47 function ProcessResponse(callFunc, obj) {
     48     if (obj.readyState == 4 && obj.status == 200) {
     49         var resultData = null;
     50         var resultType = obj.getResponseHeader("Content-Type");
     51         //        switch (resultType) {
     52         //            case "image/Png" || "image/jpeg":
     53         //                resultData = obj.responseBody;
     54         //                break;
     55         //            case "text/xml; charset=gb2312" || "text/xml; charset=utf-8" || "text/xml;charset=gb2312" || "text/xml;charset=utf-8":
     56         //                resultData = obj.responseXML;
     57         //                break;
     58         //            case "text/html; charset=gb2312" || "text/html; charset=utf-8" || "text/html;charset=gb2312" || "text/html;charset=utf-8":
     59         //                resultData = obj.responseText;
     60         //                break;
     61         //            default:
     62         //                resultData = obj.responseStream;
     63         //}
     64 
     65         if (resultType == "image/Png" || resultType == "image/jpeg") {
     66             resultData = obj.responseBody;
     67         }
     68         else if (resultType == "text/xml; charset=gb2312" || resultType == "text/xml; charset=utf-8" || resultType == "text/xml;charset=gb2312" || resultType == "text/xml;charset=utf-8") {
     69             resultData = obj.responseXML;
     70         }
     71         else if (resultType == "text/html; charset=gb2312" || resultType == "text/html; charset=utf-8" || resultType == "text/html;charset=gb2312" || resultType == "text/html;charset=utf-8") {
     72             resultData = obj.responseText;
     73         }
     74         else {
     75             resultData = obj.responseStream;
     76         }
     77 
     78         if (resultData) {
     79             //执行回调函数
     80             callFunc(resultData);
     81         }
     82         else {
     83             alert("接收服务器数据异常!");
     84         }
     85         //设置资源失效
     86         delete resultData;
     87         delete resultType;
     88         //释放资源
     89         //CollectGarbage();
     90         //AJax.Dispose();
     91         setTimeout(CollectGarbage, 3);
     92     }
     93 }
     94 
     95 AJax.prototype.Handle = function (callFunc, obj) {
     96     this.xmlHttpRequest.onreadystatechange = function () { ProcessResponse(callFunc, obj); };
     97 };
     98 
     99 //在IE最小化时,IE会主动调用一次GC,
    100 AJax.prototype.Dispose = function () {
    101     if (this.xmlHttpRequest) {
    102         this.xmlHttpRequest = null;
    103         //delete this.xmlHttpRequest;
    104         //释放资源(由于资源还在上下文中,立即调用GC并不会释放资源,故延时call GC)
    105         //CollectGarbage();
    106         setTimeout(CollectGarbage, 3);
    107     }
    108 };
    109 
    110 AJax.prototype.SendRequest = function () {
    111     if (this.CheckUrl()) {
    112         this.Init();
    113         if (this.CallFunc) {
    114             if (this.xmlHttpRequest) {
    115                 this.xmlHttpRequest.open("POST", this.Url, true);
    116                 this.xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
    117                 //this.xmlHttpRequest.onreadystatechange = ProcessResponse;
    118                 this.Handle(this.CallFunc, this.xmlHttpRequest);
    119                 this.xmlHttpRequest.send(this.DataContent);
    120             }
    121             else {
    122                 this.xmlHttpRequest.abort();
    123                 this.Dispose();
    124                 alert("异步请求对象创建失败!");
    125             }
    126         }
    127         else {
    128             this.Dispose();
    129             alert("请设置回调函数!");
    130         }
    131     }
    132     else {
    133         alert("非法地址!");
    134     }
    135 };
    136 
    

    2、后台处理页面代码:

     1 protected void Page_Load(object sender, EventArgs e)
     2         {
     3             DataAction();
     4         }
     5 
     6         private void ResponseWrite(string contentType, string chartSet, string contentEncoding, Object obj)
     7         {
     8             //Response.ContentType = "text/html";
     9             //Response.Charset = "gb2312";
    10             //Response.ContentEncoding = Encoding.GetEncoding("GB2312");
    11             //Response.Write(ModelAdd());
    12             //Response.Flush();
    13             //Response.End();
    14 
    15             Response.ContentType = contentType;
    16             Response.Charset = chartSet;
    17             Response.ContentEncoding = Encoding.GetEncoding(contentEncoding);
    18             Response.Write(obj);
    19             Response.Flush();
    20             //Response.End();
    21             HttpContext.Current.ApplicationInstance.CompleteRequest();
    22         }
    23 
    24         private void DataAction()
    25         {
    26             string actionFlag = Request.QueryString["flag"];
    27             switch (actionFlag)
    28             {
    29                 case "add":
    30                     ModelAdd();
    31                     break;
    32                 case "img":
    33                     ImgUpdate();
    34                     break;
    35 
    36                 default:
    37                     break;
    38             }
    39 
    40         }
    41 
    42         #region ADDMODEL
    43 
    44         private void ModelAdd()
    45         {
    46             string strJson = "";
    47             MODEL_Meidicine model = DataAdd();
    48             MemoryStream ms = new MemoryStream();
    49             DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(MODEL_Meidicine));
    50             json.WriteObject(ms, model);
    51             strJson = Encoding.UTF8.GetString(ms.ToArray());
    52             ms.Flush();
    53             ms.Close();
    54 
    55             ResponseWrite("text/html", "gb2312", "GB2312", strJson);
    56         }
    57 
    58         private MODEL_Meidicine DataAdd()
    59         {
    60             MODEL_Meidicine model = new MODEL_Meidicine();
    61             model.Id = (new Random()).Next(1000);
    62             model.Namec = "胰岛素注射剂";
    63             model.Newid = Guid.NewGuid().ToString();
    64             model.Medicinemodel = "粉针剂";
    65             model.Outlookc = "0.6/mg";
    66             model.Memo2 = "3";
    67             model.Jkycj = "江苏正大天晴药业股份有限公司";
    68             return model;
    69         }
    70 
    71 
    72         #endregion
    73 
    74         #region IMGUPDATE
    75 
    76         private void ImgUpdate()
    77         {
    78             string imgUrl = "";
    79             Random rad = new Random();
    80             imgUrl = "Images/" + rad.Next(10) + ".JPG";
    81             ResponseWrite("text/html", "utf-8", "UTF-8", imgUrl);
    82         }
    83 
    84         #endregion

    4、JSON实体类代码:

     1 [DataContract]
     2     public class MODEL_Meidicine
     3     {
     4         private string _newid;
     5 
     6         [IgnoreDataMember]
     7         public string Newid
     8         {
     9             get { return _newid; }
    10             set { _newid = value; }
    11         }
    12 
    13         private int _id;
    14         [DataMember(Name = "ID")]
    15         public int Id
    16         {
    17             get { return _id; }
    18             set { _id = value; }
    19         }
    20 
    21         private string _namec;
    22         [DataMember(Name = "NAMEC")]
    23         public string Namec
    24         {
    25             get { return _namec; }
    26             set { _namec = value; }
    27         }
    28 
    29         private string _medicinemodel;
    30         [DataMember(Name = "MEDICINEMODEL")]
    31         public string Medicinemodel
    32         {
    33             get { return _medicinemodel; }
    34             set { _medicinemodel = value; }
    35         }
    36 
    37         private string _outlookc;
    38         [DataMember(Name = "OUTLOOKC")]
    39         public string Outlookc
    40         {
    41             get { return _outlookc; }
    42             set { _outlookc = value; }
    43         }
    44 
    45         private string _memo2;
    46         [DataMember(Name = "MEMO2")]
    47         public string Memo2
    48         {
    49             get { return _memo2; }
    50             set { _memo2 = value; }
    51         }
    52 
    53         private string _jkycj;
    54         [DataMember(Name = "JKYCJ")]
    55         public string Jkycj
    56         {
    57             get { return _jkycj; }
    58             set { _jkycj = value; }
    59         }
    60 
    61 
    62 
    63     }

    3、前台显示及调用代码:

    调用脚本“

     1 <script src="Scripts/AJax.js" type="text/javascript" language="javascript"></script>
     2     <script type="text/javascript" language="javascript">
     3         //var temp = msg();
     4         //        var temps = new msg();
     5         //        alert(temps.kk);
     6         //AJax.SendRequest();
     7 
     8 
     9         function Update() {
    10             var aJax = new AJax();
    11             aJax.Url = "AJaxHandle.aspx?flag=add";
    12             aJax.DataContent = "txt=" + escape("你好") + "&key=sf46bs9vftr";
    13             aJax.CallFunc = function (result) { UIAction(result); };
    14             aJax.SendRequest();
    15         }
    16 
    17         function UIAction(res) {
    18             var obj = eval('(' + res + ')');
    19             var tbl = document.getElementById("tblResult");
    20             var row = tbl.insertRow(tbl.rows.length);
    21             row.insertCell(0).innerText = obj.ID;
    22             row.insertCell(1).innerText = obj.NAMEC;
    23             row.insertCell(2).innerText = obj.MEDICINEMODEL;
    24             row.insertCell(3).innerText = obj.OUTLOOKC;
    25             row.insertCell(4).innerText = obj.MEMO2;
    26             row.insertCell(5).innerText = obj.JKYCJ;
    27         }
    28 
    29         function updateImg() {
    30             var aJax = new AJax();
    31             aJax.Url = "AJaxHandle.aspx?flag=img";
    32             aJax.DataContent = "txt=" + escape("你好") + "&key=sf46bs9vftr";
    33             aJax.CallFunc = function (result) { document.getElementById("imgObj").src = result; };
    34             aJax.SendRequest();
    35         }
    36 
    37 
    38     </script>

    html代码:

     1 <div>
     2         <table id="tblResult" style="border- 12px; border-color: Black;">
     3             <thead>
     4                 <th style=" auto;">
     5                     ID
     6                 </th>
     7                 <th style=" auto;">
     8                     NAMEC
     9                 </th>
    10                 <th style=" auto;">
    11                     MEDICINEMODEL
    12                 </th>
    13                 <th style=" auto;">
    14                     OUTLOOKC
    15                 </th>
    16                 <th style=" auto;">
    17                     MEMO2
    18                 </th>
    19                 <th style=" auto;">
    20                     JKYCJ
    21                 </th>
    22             </thead>
    23             <tbody>
    24                 <td>
    25                     0
    26                 </td>
    27                 <td>
    28                 </td>
    29                 <td>
    30                 </td>
    31                 <td>
    32                 </td>
    33                 <td>
    34                 </td>
    35                 <td>
    36                 </td>
    37             </tbody>
    38         </table>
    39         <div style="text-align: center;">
    40             <img id="imgObj" src="" alt="随机更新" />
    41         </div>
    42         <div style="text-align: center;">
    43             <input id="" type="button" onclick="Update();" value="更新" />
    44             <input id="" type="button" onclick="updateImg();" value="更新图片" />
    45         </div>
    46     </div>
  • 相关阅读:
    ASP的生成指定格式的GUID
    Principle
    Email icon generator
    Google 's Gmail
    防火墙
    注释
    对敏捷开发方法的一些疑问
    Faq about multimedia
    BSTR、char*和CString转换
    dshow配置环境vc6
  • 原文地址:https://www.cnblogs.com/backbone/p/4513137.html
Copyright © 2011-2022 走看看