锐英源软件
第一信赖

精通

英语

开源

擅长

开发

培训

胸怀四海 

第一信赖

当前位置:锐英源 / 软件开发培训 / 英语翻译 ASP.NET开源 / 最易学的jQuery和AJAX结合编程引导。
服务方向
ɋ¹¤ׇŜ˽¾ݴ¦m
ɋ¹¤ׇŜƠѵ
kaldi˽¾ޗ¼±¸
СԯזԯӴʶ±�>
ԯӴʶ±𲫗¢
ԯӴʶ±񏶍³
ԯӴʶ±񗫎ŗԼ/a>
kaldi¿ª·¢¼¼˵·�>
ɭ¼�/dt>
Ջ¶¯¿ٖƿ¨ʏλ»�
»�¹¤ɭ¼�/dd>
ɭ¼�ᑵ
Java °²׿ӆ¶¯¿ª·¢
VC++
C#ɭ¼�/dd>
»㲠ºΆƽຯa>
Ƚ¶¯¿ª·¢
联系方式
固话:0371-63888850
手机:138-0381-0136
Q Q:396806883
微信:ryysoft

Introduction介绍

Have an ASP.NET 1.1 site that you want to quickly add some AJAX functionality to? Could you use the new Microsoft AJAX release? Of course, but you could also use any of the popular JavaScript libraries available and do it yourself just as easily. In some cases, you may not want to use the new Microsoft AJAX. Luckily, there are plenty of other good (and easy) alternatives!使用AJAX,有很多选择。 This article will demonstrate how to use a popular JavaScript library (jQuery) to add AJAX capabilities to your application with a minimal amount of code.本文演示了以最小的代码代价情况下,用流行的JavaScript library (jQuery)来实现AJAX功能。

Background背景

So, why wouldn't you upgrade to ASP.NET 2.0 and just use the new AJAX functionality provided by Microsoft? Well, if your site is deployed and working – you may not want (or be able to) upgrade to ASP.NET 2.0 as quickly as you would like to. You could, of course, use the new Microsoft AJAX functionality in your ASP.NET 1.1 application (as noted in this article), but just in case you don't want to – this article offers another alternative. 如果不想从ASP.NET1.1升级到ASP.NET2.0,这里提出了个选择。
Most of the popular JavaScript libraries available today have AJAX functionality built right in, and it's usually a snap to use. Some of the most popular JavaScript libraries are Prototype, Yahoo User Interface Library (YUI), andjQuery. jQuery happens to be my personal favorite, so that's what this sample will use. I could wax poetic on why I like it so much, but as that isn't the point of this article, I'll let you decide for yourself. Whichever one you choose, the process outlined in this article shouldn't vary all that much. With all of that out of the way, let's get started.jQuery是我的最爱,本例里也使用了它。我可以展示喜欢它的原因。
This sample will utilize a popular JavaScript library called jQuery to provide almost everything we need to utilize AJAX in this sample. If you are unfamiliar with jQuery, it is an extremely lightweight JavaScript library that has changed the way that I write JavaScript. It's made the process a lot more enjoyable as well.如果你不熟悉jQuery,只需要知道它是轻量级的JavaScript库,它也改正了我写JavaScript的方式。

Using the code代码用法

The attached demo project includes both samples described here. To use it, unzip it to a directory on your system, and then create a Virtual Directory in IIS called "AJAXJQuerySample", and point it to the folder that contains the unzipped files. Next, just open the AJAXJQuerySample.csproj file!附带的示例项目包含了本文介绍的例子。要使用它,解压到本地硬盘目录里,在IIS里创建一个名称为“AJAXJQuerySampl”的虚拟目录,让该目录指向解压的本地目录,再打开AJAXJQuerySample.csproj文件

Pre-requisites前提

First, you'll need to download the latest version of the jQuery JavaScript library from here (version 1.1 at the time of this writing). While you're doing this, you might want to bookmark the jQuery site for a quick browsing later on. One of the reasons that this is my library of choice is because of the extremely active user base. The forums are very active, and questions are usually answered very quickly. There are also tons of "plug-ins" that other users have made for jQuery that do just about anything you can think of.首先下载最新版本的jQuery库。

Sample 1: Get the current date and time from the server示例1:从服务器上获取当前日期和时间

For this first example, we'll be creating a simple page that grabs the current time from the server. To begin, we'll need to include the jQuery file in our "Default.aspx" page, like so:创建简单的页面来抓取服务器当前时间。先包含jQuery文件。
<script type="text/javascript" src="jquery-1.1.js">
Then, we'll use jQuery to setup the AJAX action that we want to happen when the user clicks on the "Get Server Time" link:用jQuery封装AJAX动作,这个动作在点击"Get Server Time"链接时触发。
$(function() {
//this code is executed when the page's onload event fires

    $("a#runSample1").click(function() {
$.get("GetServerTime.aspx", function(response) {
alert(response);
});
});
});
In case you're wondering what you're looking at, let's go over it line by line. The first line is executed when the page's "onload" event is fired:第一行在onload事件执行时会触发。
$(function() {
Then, we look for the "a" tag with an ID of "runSample1", and then bind to the "onclick" event:查找ID为”runSample1”的”a”标签,绑定onclick事件。
$("a#runSample1").click(function() {
Now that we're bound to the link's "onclick" event, we can write the code that we want to execute when it is clicked. The following line is executed when the link's "onclick" event is fired. This line makes a call to the "GetServerTime.aspx" page (we'll create that shortly), and returns the output of that page into the "response" variable. Then, we display the response in an alert box.现在已经绑定链接的onclick事件。下面代码会调用"GetServerTime.aspx"页面,返回输出到"response"变量里。接着用alert窗口显示回复。
$.get("GetServerTime.aspx", function(response) {
alert(response);
});
Now, let's take a look at the "GetServerTime.aspx" page. For this page, we don't want any HTML to be output, so we'll remove all of the HTML and just leave the reference to the code-behind file.看"GetServerTime.aspx"内容。因为不想要任何HTML输出,所以删除了所有HTML标签,只保留了code-behind文件的引用。
<%@ Page language="c#" Codebehind="GetServerTime.aspx.cs"
AutoEventWireup="false" Inherits="AJAXJQuerySample.GetServerTime" %>
(**Note: You could also point to an HttpHandler, but in the interest of brevity, this example will follow this method.) The code-behind file should have the following code:
private void Page_Load(object sender, System.EventArgs e)
{
Response.Expires = -1;
//required to keep the page from being cached on the client's browser

    Response.ContentType = "text/plain";
Response.Write(DateTime.Now.ToString());
Response.End();
}
The first thing we need to do is keep the page from being cached in the browser:下面会让浏览器的本地缓冲失效
Response.Expires = -1;
The response of a "GET" request is cached by default, so to make sure that our example brings back the current time each time it is clicked, this line is crucial. The next few lines change the content type to plain text, get the current time, and writes the output:GET请求默认会缓冲,为了确保返回当前服务器时间,此行代码是关键。下面行修改内容类型为纯文本,获取当前时间,输出。
Response.ContentType = "text/plain";
Response.Write(DateTime.Now.ToString());
Response.End();
That's it! Now, we can run our sample. Click the "Get Server Time" link, and we should see the current time displayed in an alert box:点击链接,看到alert窗口显示时间了。
So, let's move on to a more complex example: saving data back to the server using an AJAX call.下面讲复杂点,用AJAX调用保存数据到服务器上。

Sample 2: Saving data to the server示例2保存数据到服务器上

As you may have noticed, in the demo project for download, the "Default.aspx" page does not have the "runat=server" attribute in the "form" tag. The reason for this is because ASP.NET doesn't allow nested formtags. HTML does, however, allow this, and because this next example will use a nested form, we need to remove the "runat=server" attribute from the "Default.aspx" page. This sample will also use one of the jQuery "plug-ins" that I disused earlier, called the "Form plug-in (with AJAX)" which you can get from here. "Default.aspx"页面里的form标签里没有"runat=server"属性。原因是ASP.NET不允许form嵌套,而HTML可以。本例子也使用了一个jQuery插件,名称为“Form plug-in (with AJAX)”。
Save the plug-in code into a file named "form.js", and include it in the "Default.aspx" page. Here is the additional HTML that we'll be adding to our "Default.aspx" file:插件保存为form.js,在default.aspx里包含它。下面是添加的html内容:
<div style="width:350px">
<div style="background:#CCC"> <a href="#" id="editName">Edit</a></div>
<div id="divView"><asp:literal id="litName" runat="server"/></div>
<div id="divEdit" style="display:none"></div>
</div>
The literal control litName will be populated from a name held in a Session variable. It is the name held in this session that we'll be editing in this example. Next is the JavaScript we'll be adding to the "Default.aspx" page for this example: litName文本控件内容来自于Session变量,Session变量在本例后面代码初始化。
$("a#editName").click(function() {
$.get("ChangeName.aspx", function(response) {
$("div#divEdit").html(response).show();
$("div#divView").hide();

var options = {
method: 'POST',
url: 'ChangeName.aspx',
after: function(response) {
$("div#divView").html(response).show();
$("div#divEdit").empty().hide();
$("a#editName").show();
}
};
//bind to form's onsubmit event
$("form#ChangeName").ajaxForm(options);

//hide the "edit" link
$("a#editName").hide();
//wire up the cancel link
$("a#lnkCancel").click(function() {
$("div#divView").show();
$("div#divEdit").empty().hide();
});
});
});
The first block of code above binds to the "onclick" event of the link with an I D of editName. When this code is executed, we'll retrieve the "ChangeName.aspx" file and display the output in the 'divEdit' div tag. We'll also hide the div tag that contains the "read only" view of this same data (the 'divView' div tag):本段代码执行时,从"ChangeName.aspx"获取内容显示到divEdit里了,也隐藏只读的数据视图div,即divView。
$("a#editName").click(function() {
$.get("ChangeName.aspx", function(response) {
$("div#divEdit").html(response).show();
$("div#divView").hide();
This last example shows one of the greatest features of jQuery: Chainability. Notice this line of code:$("div#divEdit").html(response).show();. This line finds the div tag with an ID of divEdit, sets theinnerHTML to the content of the response variable, and then shows it. To describe chainability in a nutshell: every method within jQuery returns the query object itself, allowing you to 'chain' upon it.注意jQuery的最伟大特性:链式表达式。注意此行$("div#divEdit").html(response).show();此行找到ID为divEdit的标签,设置response 的内容到这个标签的innerHTML,接着显示。对此特点概括起来说:jQuery的每个方法都返回了查询对象自己,这样允许了“串联”。
OK, so now the HTML within the "ChangeName.aspx" has been placed into the 'divEdit' div (form and all) – so now, we need to bind to the "onsubmit" event and handle it with our Form plug-in. The following code defines our desired settings for the Form plug-in using JSON in the "options" variable:现在"ChangeName.aspx"里面的HTML已经置入了divEdit标签里(form和其它全部)-下面要绑定"onsubmit"事件且处理它。下面的代码以JSON格式填充了"options"变量,这个变量定义了我们想要的Form配置。
var options = {
method: 'POST',
url: 'ChangeName.aspx',
after: function(response) {
$("div#divView").html(response).show();
$("div#divEdit").empty().hide();
}
};
Notice that the above code also specifies the code to execute when a response is received from the form submission, in the "after" keyword. Now, we can use the Form plug-in's "ajaxForm" function to bind to the form's "onsubmit" event:代码指定了Form提交时响应接收到时要执行的代码,用了”after”关键字。现在可以绑定上"onsubmit"事件了。
//bind to form's onsubmit event

$("form#ChangeName").ajaxForm(options);
Lastly, we'll hide the editName link and bind to the Cancel link's "onclick" event to get back to our previous state by clearing out the edit form, hiding the editing div tag, and showing the view div tag.最后,隐藏editName链接且绑定Cancel链接的"onclick"事件到回复到以前状态,即清除编辑form,隐藏编辑div标签,且显示视图div标签。
//hide the "edit" link

$("a#editName").hide();
//wire up the cancel link

$("a#lnkCancel").click(function() {
$("div#divView").show();
$("div#divEdit").empty().hide();
});
Now, let's take a look at the "ChangeName.aspx" page. Here's the HTML in its entirety (notice the absence of thehtml and head tags). Remember, this page will be loaded into our "Default.aspx" page, so we don't want thehtml and head tags to come with it:注意"ChangeName.aspx"页面会被载入到"Default.aspx"页面里,所以不需要带上head标签。
<%@ Page language="c#" Codebehind="ChangeName.aspx.cs"
AutoEventWireup="false" Inherits="AJAXJQuerySample.ChangeName" %>
<form id="ChangeName" method="post" runat="server">
<asp:textbox id="txtName" runat="server"/>
<input type="submit" value="Save" id="Submit1" name="Submit1"/> or
<a href="#" id="lnkCancel">Cancel</a>
</form>
And, here is the code-behind file:代码文件
protected System.Web.UI.WebControls.TextBox txtName;
private void Page_Load(object sender, System.EventArgs e)
{
if (Page.IsPostBack)
{
ProcessForm();
}
else
{
string existingName;
if (Session["testName"] == null)
{
Session["testName"] = "John Smith";
}
existingName = Session["testName"].ToString();
txtName.Text = existingName;
}
}

private void ProcessForm()
{
string newName = txtName.Text;
Session["testName"] = newName;
Response.Clear();            //clears the existing HTML
Response.ContentType = "text/plain";  //change content type
Response.Write(newName);    //writes out the new name
Response.End();             //end

}
Note that we just need to use a regular <input type=submit id="Submit1" name="Submit1"> tag to submit the form instead of an <asp:button> web control. This is because of the submission being handled by jQuery. In the code-behind, we just need to detect a postback and handle the form submission from there:只需要用常规的<input type=submit id="Submit1" name="Submit1">标签来提交form,代替了<asp:button>web 控件。因为提交由jQuery负责。在代码文件里,我们需要检测postback且处理form提交。
if (Page.IsPostBack)
{
ProcessForm();
}
else...
The "ProcessForm" method is called, which handles the form submission and outputs the updated name:输出名称
string newName = txtName.Text;
Session["testName"] = newName;
Response.Clear();  //clears the existing HTML

Response.ContentType = "text/plain";    //change content type
Response.Write(newName);                //writes out the new name
Response.End();                         //end
That's it! Now, we can run our sample. Click the "Edit" link and the new form is loaded in. Change the name and click the "Save" button, and the updated name is sent back and displayed.点击"Edit"链接,加载出新form。修改名称,点击"Save"按钮,新名称发回到服务器保存,且显示出来。
Step 1: Click the "Edit" link:
editbegin
Step 2: Change the name and click "Save":
save
Step 3: View the updated name:

edit

版权所有 Copyright(c)2004-2024 锐英源软件
统一社会信用代码:91410105098562502G 豫ICP备08007559号 最佳分辨率 1440*900
地址:郑州市金水区文化路97号郑州大学北区院内南门附近