2.JQuery AJAX

  • new ActiveXObject("Microsoft XMLHTTP")是IE中创建XMLHTTPRequest对象的方法。非IE浏览器创建方法是new XmlHttpRequest().为了兼容不同的浏览器需要编写很多代码。
  • 用JQuery的回调函数($.post(data,textStatus))中data参数为服务器返回的数据,textStatus为服务器返回状态码,textStatus为"success"表示通信成功。
  • JQuery中提供了简化ajax使用的方法。$.ajax()函数是jQuery中提供的ajax访问函数,$.post()是对$.ajax()的post方式提交ajax查询的封装,$.get()是对$.ajax()的get方式提交ajax查询的封装。推荐用post方式,因为post方式没有缓存的问题。
  • 如果有请求参数则在第二个参数用字典方式来设置。$.post("GetDate1.ashx",{"id":"2"},function(data,textStatus){}).jQuery帮我们进行了URL编码,因此参数中有中文也不用担心。
  • XMLHttpRequest对象的open方法

    XMLHttpRequest对象的open方法的第3个参数

    xmlHttpRequest.open(method,url,true or false);  

    1.发送信息的方式(post,get)

    2.发送的目标( url)

    3.发送的布尔变量 true代表异步,为false代表同步

    调用xmlHttpRequest对象的send () 把信息发送出去

    异步的回调

    onreadystatechange属性赋值来设置一个回调函数:

      xmlHttpRequest.onreadystatechange=function() {...};

    XMLHttpRequest对象的ReadyState属性值列表。

      ReadyState取值 描述

      0 描述一种"未初始化"状态;此时,已经创建一个XMLHttpRequest对象,但是还没有初始化。

      1 描述一种"发送"状态;此时,代码已经调用了XMLHttpRequest open()方法并且XMLHttpRequest已经准备好把一个请求发送到服务器。

      2 描述一种"发送"状态;此时,已经通过send()方法把一个请求发送到服务器端,但是还没有收到一个响应。

      3 描述一种"正在接收"状态;此时,已经接收到HTTP响应头部信息,但是消息体部分还没有完全接收结束。

      4 描述一种"已加载"状态;此时,响应已经被完全接收。

    当readyState=4时,

    函数会检查HTTP服务器响应的状态值。

    当HTTP服务器响应的值为200时,表示状态正常

    1. /*具体负责处理服务器返回数据的函数*/  
    2. xmlHttpRequest.onreadystatechange = function (){   
    3.         //当服务器将数据返回给客户端时,readyState状态值为4   
    4. if(xmlHttpRequest.readyState==4){     
    5.             //当服务器返回的数据是正常的数据时,status状态值为200   
    6. if(xmlHttpRequest.status==200){   
    7.                 //通过XMLHttpRequest对象的responseText属性获取   
    8.                 //服务器返回的文本信息   
    9. var returnMsg = xmlHttpRequest.responseText;   
    10.                 //这里为具体的处理方式代码
    11.              }      
    12.          }   
    13.      } 
  • 创建XMLHttpRequest用到如下函数:
 function CreateXmlHttp()
       {
         var xmlhttp;
         //非IE浏览器创建XmlHttpRequest对象
           if(window.XMLHttpRequest)
           {
               xmlhttp = new XMLHttpRequest();
           }

           //IE浏览器创建XmlHttpRequest对象
           if(window.ActiveXObject)
           {
             try
             {
                xmlhttp=new ActiveXObject("Microsoft XMLHTTP");
             }
             catch(e)
             {
                try
                {
                  xmlhttp=new ActiveXObject("msxml2.XMLHTTP");
                }catch(ex)
                {
                  alert("AJAX创建失败");
                }
             }
           }

           return xmlhttp;
       }

示例1:

   用非jQuery的方式在客户端上显示服务器的时间,服务端源码如下:

  

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

namespace AJAX1
{
    /// <summary>
    /// AJAXGetTime 的摘要说明
    /// </summary>
    public class AJAXGetTime : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
           
            context.Response.ContentType = "text/plain";
            //以下的这些都是清除缓存用的,因为用get的方法时,如果有缓存,则回应是从缓存中读取的。
            context.Response.Buffer = true;
            context.Response.Expires = 0;
            context.Response.ExpiresAbsolute = DateTime.Now.AddDays(-1);
            context.Response.AddHeader("pragma", "no-cache");
            context.Response.AddHeader("cache-control", "private");
            context.Response.CacheControl = "no-cache";
            string id = context.Request["id"];
           
            context.Response.Write(DateTime.Now.ToString()+"-->"+id);
        }

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

客户端HTML码:

  

<!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 CreateXmlHttp()
       {
         var xmlhttp;
         //非IE浏览器创建XmlHttpRequest对象
           if(window.XMLHttpRequest)
           {
               xmlhttp = new XMLHttpRequest();
           }

           //IE浏览器创建XmlHttpRequest对象
           if(window.ActiveXObject)
           {
             try
             {
                xmlhttp=new ActiveXObject("Microsoft XMLHTTP");
             }
             catch(e)
             {
                try
                {
                  xmlhttp=new ActiveXObject("msxml2.XMLHTTP");
                }catch(ex)
                {
                  alert("AJAX创建失败");
                }
             }
           }

           return xmlhttp;
       }
       function getServertime()
       {
           var xmlhttp = CreateXmlHttp();
           if (!xmlhttp) {
              alert("xmlhttp对象不存在.");
               return;
           }

         xmlhttp.open("POST","AJAXGetTime.ashx?id=测试",true);
         xmlhttp.onreadystatechange = function () {
            
           if(xmlhttp.readyState==4) //注意大小写
           {
             if(xmlhttp.status==200) {
                
                 document.getElementById("text1").value = xmlhttp.responseText;
             } else 
             {
               alert("AJAX失败.");
               return;
             }
           }
         }
         xmlhttp.send();
       }
    </script>
    <style type="text/css">
        #text1
        {
            width: 340px;
        }
    </style>
</head>
<body>
 <input type="text" id="text1" value="aa" />
 <input type="button" id="btn" value="gettime" onclick="getServertime();" />
</body>
</html>

示例2:用JQuery的方式得到如上服务器的时间,并创建一个新的服务端,用来显示汇率计算。这个操作都在同一个客户端页面上,当用户输入一定数值的人民币并选择要换算的币种(日元,美元等),点击按钮后会把这此信息提交给服务端进行计算,计算后再显示于客户端。

  汇率计算服务端:

   

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

namespace JQueryAJAX
{
    /// <summary>
    /// HV 的摘要说明
    /// </summary>
    public class HV : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string moneytype=context.Request["type"];  //目的币种类型
            int amount = Convert.ToInt32(context.Request["amount"]); //人民币数额
            float result = 0;
            if (moneytype == "1") //人民币对美元
                result = amount / 6;
            else if (moneytype == "2") //人民币对日元
                result = amount * 8;
            else if (moneytype == "3") //人民币对英镑
                result = amount / 10;
            context.Response.Write(result);
           
        }

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

客户端,记着加入jquery库

<!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 src="js/jquery-1.10.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        function btnclick() {
            $.post("AJAXGetTime.ashx?id="+encodeURI("中国"), function (data, textStatus) {
                if (textStatus == "success")
                    $("#Text1").val(data);
                else {
                  alert("从服务器端获取信息失败.");
                }

            })
      }

      function gethv() {
          var amount = $("#txtamount").val();
         
          var type = $("#type").val();
         
          $.post("HV.ashx", { "type": type, "amount": amount }, function (data
          , textStatus) {
             
              if (textStatus == "success")
                  $("#txtresult").val(data);
                else
                  alert("服务器出错");
          });
      }
    </script>
</head>
<body>

    <p>
        <input id="Text1" type="text" /><input id="Button1" type="button" 
            value="gettime" onclick="btnclick();" /></p>
    <div id="gethv">
      <input type="text" id="txtamount" />
      <select id="type">
        <option value="1">美元</option>
        <option value="2">日元</option>
        <option value="3">英镑</option>
      </select>
      <input type="button" value="计算汇率"  onclick="gethv();" />
      <input type="text" id="txtresult" />
    </div>
</body>
</html>

运行截图:

 

原文地址:https://www.cnblogs.com/yagzh2000/p/3173362.html