從零開始學習jQuery (六) AJAX快餐

來源:互聯網
上載者:User

一.摘要

本系列文章將帶您進入jQuery的精彩世界,其中有很多作者具體的使用經驗和解決方案,即使你會使用jQuery也能在閱讀中發現些許秘籍.

本篇文章講解如何使用jQuery方便快捷的實現Ajax功能.統一所有開發人員使用Ajax的方式.

二.前言

Ajax讓使用者頁面豐富起來,增強了使用者體驗. 使用Ajax是所有Web開發的必修課. 雖然Ajax技術並不複雜,但是實現方式還是會因為每個開發人員的而有所差異.jQuery提供了一系列Ajax函數來協助我們統一這種差異,並且讓調用Ajax更加簡單.

三.原始Ajax與jQuery中的Ajax

首先通過執行個體,來看一下jQuery實現Ajax有多簡單. 下面是一個使用原始Ajax的樣本:

<!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>jQuery Ajax</title>
  <script type="text/javascript">
    $(function()
    {
      var xhr = new AjaxXmlHttpRequest();
      $("#btnAjaxOld").click(function(event)
      {
        var xhr = new AjaxXmlHttpRequest();
        xhr.onreadystatechange = function()
        {
          if (xhr.readyState == 4)
          {
            document.getElementById("divResult").innerHTML = xhr.responseText;
          }
        }
        xhr.open("GET","data/AjaxGetCityInfo.aspx?resultType=html",true);
        xhr.send(null);
      });
    })

    //跨瀏覽器擷取XmlHttpRequest對象
    function AjaxXmlHttpRequest()
    {
      var xmlHttp;
      try
      {
        // Firefox,Opera 8.0+,Safari
        xmlHttp = new XMLHttpRequest();
      }
      catch (e)
      {

        // Internet Explorer
        try
        {
          xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e)
        {

          try
          {
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
          }
          catch (e)
          {
            alert("您的瀏覽器不支援AJAX!");
            return false;
          }
        }
      }
      return xmlHttp;
    }    
  </script>

</head>
<body>
  <button id="btnAjaxOld">原始Ajax調用</button><br />
  <br />
  <div id="divResult"></div>
</body>
</html>

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.