Ajax和$.ajax使用实例详解(推荐)

2019-09-14 06:52:10丽君

实例一(Ajax请求基本创建格式):

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
 <title>Ajax练习(GET,不考虑浏览器兼容性)</title>
 <script type="text/JavaScript">
  function doRequest() {
   //不考虑浏览器兼容性问题
   var xmlHttp = new XMLHttpRequest();
   //打开一个与Http服务器的连接
   xmlHttp.open("GET", "Default.aspx", true);
   //与服务器端交互
   xmlHttp.send(null);
   //监听服务器端响应状态的改变事件
   xmlHttp.onreadystatechange = function () {
    //客户端与服务器端交互完成
    if (xmlHttp.readyState == 4) {
     //服务器端返回Http状态码:200表示请求成功,404未找到,403错误
     if (xmlHttp.status == 200) {
      //获得服务器端资源
      var result = xmlHttp.responseText;
      alert(result);
     }
    }
   }
  }
 </script>
</head>
<body>
 <form id="form1" runat="server">
 <div>
  <input type="button" id="btn" value="异步请求" onclick="doRequest()" />
 </div>
 </form>
</body>
</html>
<head runat="server">
 <title>AjaxDemo实例</title>
 <script src="JS/jQuery-1.4.1-vsdoc.js" type="text/javascript"></script>
 <script type="text/javascript">
  //使用Ajax读取浏览器的工作内容 
  function readRequest() {
   //不考虑浏览器的兼容性问题
   var xmlhttp = new XMLHttpRequest();
   //打开一个与服务器相关的链接
   //发送请求
   //请求的方式(获取/发送),请求页面,是否异步
   xmlhttp.open("GET", "AjaxDemo.aspx", true);
   //发送数据
   xmlhttp.send(null);
   //接受服务器返回结果
   xmlhttp.onreadystatechange = function() {
    //请求完成
    if (xmlhttp.readyState == 4) {
     //链接成功
     if (xmlhttp.status == 200) {
      //输出浏览器的内容
      var result = xmlhttp.responseText;
      alert(result);
      window.alert("读取浏览器的内容成功!");
     }
    }
   };
  };
  function btn_Click() {
   var http = new ActiveXObject("Microsoft.XMLHTTP");
   //或者使用这一句创建 var xmlhttp = new XMLHttpRequest();
   if (!http) {
    alert("创建xmlhttp对象异常!");
    return false;
   }
   http.open("POST", "AjaxDemo.ashx", false);
   http.onreadystatechange = function() {
    if (http.readyState == 4) {
     //链接成功
     if (http.status == 200) {
      alert(http.responseText);
      document.getElementById("Text1").value = http.responseText;
     } else {
      window.alert("Ajax服务器返回错误!");
     }
    }
   };
   http.send();
  };
 </script>
</head>
<body>
 <form id="form1" runat="server">
 <div>
 <input id="Button1" type="button" value="使用Ajax读取浏览器的内容" onclick="readRequest()" />
 <br/>
  <input id="Text1" type="text" />  
  <input id="Button2" type="button" value="获取当前时间" onclick="btn_Click()"/>
 </div>
 </form>
</body>