65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 jQuery 进行 AJAX 调用的五种方法的实际工作示例

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.85/5 (18投票s)

2010年2月1日

CPOL

7分钟阅读

viewsIcon

94561

downloadIcon

1507

本文介绍了一个使用 jQuery 进行 AJAX 调用五种不同方式的工作示例。

引言

本文介绍了一个使用 jQuery 进行 AJAX 调用五种不同方式的工作示例。

背景

本文旨在简短介绍一个使用 jQuery 进行 AJAX 调用五种不同方式的工作示例。

我多年来一直在开发在 Web 浏览器上运行的应用程序,我意识到 AJAX 和 jQuery 正在接近那些长时间从事这项工作的所有程序员的最终梦想。最近,我注意到一篇由 Piao Yishi 撰写的优秀文章,“Five Ways to Make AJAX Calls with jQuery”。我的文章是 Piao 文章中描述的五种方式的工作示例,如果您对我的文章感兴趣,强烈建议您阅读 Piao 的文章。

jQuery 是一个客户端脚本库,因此它完全独立于开发环境,无论它是 ASP.NET、J2EE、PHP 还是任何其他平台。Visual Studio 对我来说已经触手可及,因此示例以 ASP.NET 项目的形式创建。借鉴 Piao 的文章,本文演示的五种方法如下:

Five Methods

jQuery AJAX 调用非常强大且灵活。本文中的代码仅用于演示 jQuery 功能的一个方面,即检索 HTML 片段并使用上述五种方法将其插入到主 ASP.NET 页面的内容中。如果以后有时间,我可能会写其他文章来讨论客户端和服务器端对 XML 和 JSON 内容的处理。

示例代码是在 Visual Studio 2008 中使用 jQuery 1.4 开发的。我没有在其他版本上进行测试,但我认为版本对于我们要讨论的五种 AJAX 方法没有区别。

供 jQuery 调用检索的 HTML 片段

我将介绍五种 jQuery 方法来检索由 HTML 片段表示的示例学生信息列表。HTML 片段是一个 HTML 表格。本文中的所有 jQuery 调用都将获取此 HTML 表格并将其插入到调用的 ASP.NET 页面中。在服务器端,学生记录列表中的信息由类“StudentRecords”表示,如下所示:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
 
namespace jQueryFiveAjaxCalls.StudentRecordArchive
{
    public class StudentRecords : DataTable
    {
        public StudentRecords(int NoOfRecordsToRetrieve): base()
        {
            Columns.Add("ID", System.Type.GetType("System.Int32"));
            Columns.Add("Name", System.Type.GetType("System.String"));
            Columns.Add("Score", System.Type.GetType("System.Int32"));
            Columns.Add("Comment", System.Type.GetType("System.String"));
            Columns.Add("Evaluation Time", System.Type.GetType("System.DateTime"));
 
            Random rd = new Random();
            for (int Idex = 1; Idex <= NoOfRecordsToRetrieve; Idex++)
            {
                string Name = "Student Name No." + Idex.ToString();
                int Score = System.Convert.ToInt16(60 + rd.NextDouble() * 40);
                string Comment = "Comment on " + Name + " is extremely bad";
                if (Score < 80)
                {
                    Comment = "Comment on " + Name + " is very good by the teacher";
                }
 
                DataRow row = Rows.Add();
                row["ID"] = Idex;
                row["Name"] = Name;
                row["Score"] = Score;
                row["Comment"] = Comment;
                row["Evaluation Time"] = System.DateTime.Now;
            }
        }
    }
}

此类表示 ADO.NET DataTable。通过创建此类的实例并将一个整数(表示学生记录数)传递给构造函数,我们可以获得一个填充有随机生成的示例学生记录信息的 DataTable

HTML 片段由 ASP.NET 文件“*StudentRecordsHTMLFragment.aspx*”使用 DataTable 类型的 StudentRecords 生成。一个正常的 ASP.NET 页面将包含所有 HTML 标签,例如“<html>”和“<body>”等。为了获得一个只有 HTML“<table>”的干净 HTML 片段,我必须修改默认的 ASP.NET 页面生成过程。以下是“*StudentRecordsHTMLFragment.aspx*”的代码隐藏文件:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
 
namespace jQueryFiveAjaxCalls.StudentRecordArchive
{
    public partial class StudentRecordsHTMLFragment : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            String ReturnJson = Request.QueryString["RETURNJSON"];
            String NoOfRecordsToRetrieve = Request.QueryString["NRECORD"];
 
            if (NoOfRecordsToRetrieve == null)
            {
                NoOfRecordsToRetrieve = Request.Form["NRECORD"];
            }
 
            StudentRecords Records = 
              new StudentRecords(System.Convert.ToInt16(NoOfRecordsToRetrieve));
 
            DataGrid DG = new DataGrid();
            DG.CellPadding = 14;
            DG.Style.Add("font-size", "10px");
            DG.HeaderStyle.BackColor = System.Drawing.Color.Brown;
            DG.HeaderStyle.ForeColor = System.Drawing.Color.White;
            DG.HeaderStyle.Font.Bold = true;
 
            DG.Attributes.Add("bordercolor", "black");
            DG.DataSource = Records;
            DG.DataBind();
 
            StringBuilder SB = new StringBuilder();
            HtmlTextWriter TW = 
              new HtmlTextWriter(new System.IO.StringWriter(SB));
            DG.RenderControl(TW);
 
            string ContentType = "text/html";
            string Content = SB.ToString();
            if (ReturnJson == "True")
            {
                ContentType = "text/x-json";
                StringBuilder JsonSB = new StringBuilder();
                JsonSB.Append("{\"TB\": \"");
                JsonSB.Append(SB.Replace("\"", "'").Replace(
                  "\t", "").Replace("\r", "").Replace("\n", ""));
                JsonSB.Append("\"}");
                Content = JsonSB.ToString();
            }
 
            Response.ContentType = ContentType;
            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            Response.OutputStream.Write(encoding.GetBytes(Content), 0, 
                                        Content.Length);
        }
    }
}

在上面的代码中,我们首先从调用者那里获取两个参数,它们将是本文中的 jQuery 方法。需要获取的两个参数是:

  • RETURNJSON”,指示 HTML 表格是否将在 JSON 对象中返回。
  • NRECORD”,指示要在 HTML 表格中包含的学生记录数。

您可能会注意到 NRECORD 是通过 Request.QueryString()Request.Form() 检索的。这是因为有些 jQuery 调用使用 GET 方法,而其他调用使用 POST 方法。为了确保 *StudentRecordsHTMLFragment.aspx* 始终知道需要包含多少学生记录在 HTML 片段中,同时使用了 Request.QueryString()Request.Form()。当代码知道需要多少学生记录时,它会初始化一个 StudentRecords 对象并将其绑定到一个 ASP.NET DataGrid 对象。从 DataGrid 对象,我们可以获得 HTML 表格的 HTML 字符串,并将该文本字符串返回给调用者。当调用者需要一个简单的 HTML 片段时,代码以“text/html”的内容类型返回给调用者。如果调用者需要一个 JSON 对象,则在对数据进行一些处理后返回一个 JSON 对象。

主 ASP.NET 文件“Default.aspx”

现在,让我们看一下“*Default.aspx*”文件。由于 jQuery 是一个客户端脚本库,常用的 ASP.NET 特定功能在此文章中不再有用,因此我禁用了视图状态,并删除了 ASP.NET Web 窗体,因此 *Default.aspx* 永远不会“回发”。

<%@ Page Language="C#" AutoEventWireup="true" 
    EnableViewState="false" CodeBehind="Default.aspx.cs" 
    Inherits="jQueryFiveAjaxCalls.Default" %>
 
<!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 runat="server">
    <title>Demo Code for 5 Ajax Calls Using jQuery</title>
    <link rel="SHORTCUT ICON" href="Images/icon_tong.ico" />
    <link href="Styles/AppStyles.css" rel="stylesheet" type="text/css" />
    <script src="JS/jquery-1.4.1.min.js" type="text/javascript"></script>
 
<script language="javascript" type="text/javascript">
    $(document).ready(function() {
        var $target = $("#MainContent");
        var $resource = 
          "StudentRecordArchive/StudentRecordsHTMLFragment.aspx";
        var $jsresource = "JS/ExampleScript.js";
        var $information = $("#lblInformation");
        var $informationDefaultTextNotSelected =
            "Please select the number of records to retrieve " + 
            "and click on one of the links above ...";
        var $informationDefaultTextSelected =
            "Please click on one of the links above ...";
        var $ajax_load = "<img src='Images/ajax-loader.gif' alt='Loading ...'/>";
 
        $.ajaxSetup({ cache: false });
 
        $("#selNoOfStudentRecords").change(function() {
            $target.html("");
            if ($('#selNoOfStudentRecords').val() == "*") {
                $(":button").attr("disabled", true);
                $(":button").removeClass("ButtonStyle");
                $(":button").addClass("ButtonDisabled");
                $information.html($informationDefaultTextNotSelected);
                
            } else {
                $(":button").attr("disabled", false);
                $(":button").removeClass("ButtonDisabled");
                $(":button").addClass("ButtonStyle");
                $information.html($informationDefaultTextSelected);
            }
        }).change();
 
        $("a").hover(function() {
            this.style.color = "red";
        }, function() {
            this.style.color = "";
        });
 
        $("#btnClear").click(function(e) {
            e.preventDefault();
 
            $target.html("");
            $information.html($informationDefaultTextSelected);
        });
 
        $("#btnUseLoad").click(function(e) {
            e.preventDefault();
 
            var $nRecord = $('#selNoOfStudentRecords').val();
            $target.html($ajax_load).load($resource, { NRECORD: $nRecord });
            $information.html("Information retrieved by load method ...");
        });
 
        $("#btnUseGet").click(function(e) {
            e.preventDefault();
 
            var $nRecord = $('#selNoOfStudentRecords').val();
            $target.html($ajax_load);
            $.get($resource, { NRECORD: $nRecord }, function($x) {
                $target.html($x);
                $information.html("Information retrieved by get method ...");
            });
        });
 
        $("#btnUsePost").click(function(e) {
            e.preventDefault();
 
            var $nRecord = $('#selNoOfStudentRecords').val();
            $target.html($ajax_load);
            $.post($resource, { NRECORD: $nRecord }, function($x) {
                $target.html($x);
                $information.html("Information retrieved by post method ...");
            });
        });
 
        $("#btnUseGetJSON").click(function(e) {
            e.preventDefault();
 
            var $nRecord = $('#selNoOfStudentRecords').val();
            $target.html($ajax_load);
 
            $.getJSON($resource, { NRECORD: $nRecord, RETURNJSON: "True" }, function($x) {
                $target.html($x.TB);
                $information.html("Information retrieved by getJSON method ...");
            });
        });
 
        $("#btnUseGetScript").click(function(e) {
            e.preventDefault();
 
            var $nRecord = $('#selNoOfStudentRecords').val();
            $target.html($ajax_load);
            $.getScript($jsresource, function() {
                $.loadStudentHtmlFragment($target, $resource, { NRECORD: $nRecord });
                $information.html("Information retrieved by " + 
                                  "getScript method and run this script ...");
            });
        });
 
    });
    
</script>
</head>
 
<body>
<div>
<div class="AppTitle">A Working Example of the Five Ways to Make jQuery Ajax Calls</div>
<div class="AuthorTitle"><asp:Label 
   ID="lblAuthorInformation" runat="server"></asp:Label></div>
 
<div>
<table style="width: 100%" cellpadding="0px" cellspacing="0px">
    <tr>
        <td style="white-space: nowrap" align="left">
            <span>
                <span>
                    <input type="button" id="btnUseLoad" 
                        class="ButtonStyle" value="Call by load (...)" />
                </span>
                <span>
                    <input type="button" id="btnUseGet" 
                        class="ButtonStyle" value="Call by get (...)" />
                </span>
                <span>
                    <input type="button" id="btnUsePost" 
                        class="ButtonStyle" value="Call by post (...)" />
                </span>
                <span>
                    <input type="button" id="btnUseGetJSON" 
                        class="ButtonStyle" value="Call by getJSON (...)" />
                </span>
                <span>
                    <input type="button" id="btnUseGetScript" 
                        class="ButtonStyle" value="Call by getScript (...)" />
                </span>
                <span>
                    <input type="button" id="btnClear" 
                        class="ButtonStyle" value="Clear" />
                </span>
            </span>
        </td>
        <td>   </td>
        <td style="white-space: nowrap">
            <span style="float: right">
                <span>
                    <span>Select the number of records to retrieve  </span>
                    <span>
                        <select id="selNoOfStudentRecords" class="SmallText">
                            <option value="*">** Please select **</option>
                            <option value="5">5</option>
                            <option value="10">10</option>
                            <option value="20">20</option>
                            <option value="50">50</option>
                        </select>
                    </span>
                </span>
            </span>
        </td>
    </tr>
</table>
</div>
 
<div class="Information"><label id="lblInformation"></label></div>
<div id="MainContent" class="MainContent" 
  style="width: 100%; float: left; text-align: left"></div>
</div>
<div class="Copyright">Copy right: The Code Project Open License (CPOL)</div>
</body>
</html>

在 *Default.aspx* 的 HTML 部分,您可以看到我们只有几个功能性的视觉组件:

  1. 五个按钮,每个按钮触发一个使用其中一种 AJAX 方法的 jQuery 调用。
  2. 一个选择框,从中选择学生记录的数量。
  3. 一个 id 为“MainContent”的“div”;这是 HTML 片段插入到“*Default.aspx*”中的位置。

本文中大多数 AJAX 调用方法的使用都相当直接,除了“$.getScript()”和“$.getJSON()”。这是因为这两种方法实际上不是为加载 HTML 片段而设计的。为了在本文中演示如何使用它们,我还是让它们加载 HTML 片段,因此我需要给它们一些详细的解释。

jQuery 方法“$.getScript()”和“$getJSON()”

jQuery 方法“$.getScript()”旨在以 AJAX 方式从服务器加载一些 JavaScript。在本文中,加载的脚本是以下内容:

$.loadStudentHtmlFragment = function($target, $url, $data) {
    $target.load($url, $data);
}

这个 JavaScript 片段是一个简单的函数“$.loadStudentHtmlFragment()”,它使用 jQuery load() 方法加载 HTML 片段并将其插入到 *Default.aspx* 中。如果您仔细阅读代码,您会注意到 $target 引用 ID 为 MainContentdiv 对象。$.getScript() 方法在 *Default.aspx* 中的使用如下:

$("#btnUseGetScript").click(function(e) {
 e.preventDefault();
 
 var $nRecord = $('#selNoOfStudentRecords').val();
 $target.html($ajax_load);
 $.getScript($jsresource, function() {
                $.loadStudentHtmlFragment($target, 
                        $resource, { NRECORD: $nRecord });
                $information.html("Information retrieved " + 
                  "by getScript method and run this script ...");
 });
});

当点击触发调用 $.getScript() 的按钮时,首先调用 $.getScript() 方法加载包含 $.loadStudentHtmlFragment() 函数定义的脚本文件,然后调用 $.loadStudentHtmlFragment() 来加载 HTML 片段。

$.getJSON() 方法不是为加载 HTML 片段而设计的。但是,在 *StudentRecordsHTMLFragment.aspx* 文件中,我们包含了将 HTML 片段作为 JSON 对象返回的选项,因此我们仍然可以使用 jQuery 的 $.getJSON() 来获取 JSON 对象,然后从 JSON 对象中获取 HTML 片段。以下是本文中 $.getJSON() 的使用方式:

$("#btnUseGetJSON").click(function(e) {
    e.preventDefault();
 
    var $nRecord = $('#selNoOfStudentRecords').val();
    $target.html($ajax_load);
 
    $.getJSON($resource, { NRECORD: $nRecord, RETURNJSON: "True" }, function($x) {
        $target.html($x.TB);
        $information.html("Information retrieved by getJSON method ...");
    });
});

运行 ASP.NET 应用程序

如果您下载本文中的源代码,并将 *Default.aspx* 设置为启动页,则可以调试运行应用程序。如果一切正常,您应该会看到所有五种方法都能正常工作。下面的屏幕截图显示了调用 $.getJSON() 方法检索五个随机生成学生信息的the result of calling the $.getJSON() method to retrieve the information for five randomly generated students

Run Application

此 ASP.NET 应用程序设计用于在 Web 浏览器最大化时使用。上图是在浏览器调整大小以适应本文时拍摄的,因此布局略有偏差。如果您运行应用程序并最大化浏览器,它看起来会比您在这里看到的要漂亮得多。

关注点

  1. 以 AJAX 风格的调用与服务器交换信息是 Web 应用程序开发向前迈出的一大步。借助 jQuery,这变得非常容易且易于管理。它使传统的 Web 应用程序能够与 Silverlight 和 Flex 等 RIA 保持竞争力,尽管不应将 RIA 视为非传统。
  2. 本文使用的五种 jQuery AJAX 方法是 $.ajax() 方法的包装器。包装器非常薄,所以我们应该很容易使用 $.ajax()。如果愿意,您可以直接使用 $.ajax()
  3. $.getJSON()$getScript() 方法并非为加载 HTML 片段而设计。在本文中,我只是设法让它们完成了它们不擅长的工作,但不知何故它们起作用了。
  4. jQuery 是一个强大的工具;当与其他技术结合使用时,我们可以实现许多有益的事情,例如以更安全、更灵活的方式将配置信息从托管 Web 应用程序传递到 Silverlight 应用程序。
  5. 在我自己的测试中,jQuery 在不同的浏览器中运行得非常好。我在 IE、Firefox 和 Google Chrome 中测试了此应用程序。它在这三个浏览器中都能正常工作,但在 Firefox 中,按钮控件中文本的下划线没有显示。这是样式问题,而不是 jQuery 问题。
  6. 除了调用这五种方法之外,该应用程序还使用了一些其他的 jQuery 功能。如果您想引用代码,应该注意这一点。

历史

这是本文的第一个修订版。

© . All rights reserved.