使用AjaxPro實現(xiàn)無刷新數(shù)據(jù)檢測
使用AjaxPro實現(xiàn)無刷新數(shù)據(jù)檢測
Ajax(Asynchronous JavaScript and XML,異步JavaScript 和XML)的應(yīng)用,可以創(chuàng)建更好、更快、以及交互性更強的 Web 應(yīng)用程序。利用AjaxPro可以輕松創(chuàng)建Ajax應(yīng)用。本文主要總結(jié)一下AjaxPro的使用步驟,并實現(xiàn)Ajax無刷新檢測數(shù)據(jù)的簡單功能。
在傳統(tǒng)方式中,用戶注冊的時候,常常需要用戶填寫完整個表單,再提交給服務(wù)器。當系統(tǒng)檢測該用戶名已存在,便返回提示用戶,并需要重新填寫整個表單,用戶體驗很不好。
而使用Ajax技術(shù),在用戶注冊過程中,當用戶輸入了想注冊的用戶名后,鼠標離開編輯框,系統(tǒng)就檢測該用戶名是否存在,并立即提示用戶該用戶名是否可用?,F(xiàn)在的網(wǎng)站基本都采取了這種方法,避免傳統(tǒng)方式的弊端,提升用戶體驗。如圖所示,163郵箱的注冊界面。
Ajax的實現(xiàn)方式,通??梢苑譃橐韵氯N:
1、利用純粹的JavaScript實現(xiàn); 2、利用微軟自帶的Ajax控件庫實現(xiàn); 3、利用第三方類庫實現(xiàn),如AjaxPro; 這里介紹第三種方法,使用AjaxPro實現(xiàn)無刷新數(shù)據(jù)檢測。 |
我要實現(xiàn)的是一個添加單詞的功能,當鼠標離開單詞輸入框時,檢測單詞數(shù)據(jù)庫中是否已存在該單詞,并給出相應(yīng)提示。(同用戶注冊原理一致)。
1、獲取AjaxPro
AjaxPro是免費的Ajax類庫,官網(wǎng)是ajaxpro.info,現(xiàn)在搬到了微軟的開源托管網(wǎng)站CodePlex上,即ajaxpro.codeplex.com。
當前***版為9.2.17.1,單擊Download,下載完成后,解壓9.2.17.1_DLL.zip,得到如圖所示的五個文件。我們將使用AjaxPro.2.dll和web.config配置文件。
2、添加引用
為項目添加AjaxPro的引用。右鍵項目下的“引用”目錄,添加引用,瀏覽找到AjaxPro.2.dll,確定。
3、配置web.config
為網(wǎng)站的web.config添加AjaxPro的配置信息,主要添加三部分內(nèi)容(具體代碼參考AjaxPro壓縮包中的web.config文件)。
1)在webconfig —— <configuration> —— <configSections>節(jié)點下,添加如下代碼:
- <!--Ajax配置信息 A-->
- <sectionGroup name="ajaxNet">
- <!--
- If you are using Microsoft .NET 1.1 please remove the two attributes
- requirePermission and restartOnExternalChanges, they are only supported
- with .NET 2.0.
- -->
- <section name="ajaxSettings"
- type="AjaxPro.AjaxSettingsSectionHandler,AjaxPro.2"
- requirePermission="false"
- restartOnExternalChanges="true"
- />
- </sectionGroup>
2)在webconfig —— <configuration>節(jié)點下,添加ajaxNet節(jié)點,即如下代碼:
- <!--Ajax配置信息 B-->
- <ajaxNet>
- <ajaxSettings>
- <urlNamespaceMappings useAssemblyQualifiedName="false" allowListOnly="false">
- <!--
- Set the attribute useAssemblyQualifiedName to true to enable
- use of assemblies placed in the GAC by using the full assembly
- qualified name.
- To hide internal knowledge of assemblies, classes and namespace
- you can override the name of the virtual http endpoints.
- <add type="Namespace.Class1,Assembly" path="mypath" />
- -->
- </urlNamespaceMappings>
- <jsonConverters includeTypeProperty="true">
- <!--
- This section can be used to add new IJavaScriptConverters to the
- Ajax.NET Professional engine. If you want to disable built-in
- converters you can use the remove tag.
- <remove type="Namespace.Class1,Assembly"/>
- <add type="Namespace.Class2,Assembly"/>
- <add type="AjaxPro.BitmapConverter,AjaxPro.2" mimeType="image/jpeg" quality="100"/>
- -->
- </jsonConverters>
- <!--
- Set the enabled attribute to true to get Stack, TargetSize and Source
- information if an exception has been thrown.
- -->
- <debug enabled="false" />
- <!--
- This is the default configuration used with Ajax.NET Professional. You
- can put there your static JavaScript files, or remove the path attribute
- to completly disable the files.
- <scriptReplacements>
- <file name="prototype" path="~/ajaxpro/prototype.ashx" />
- <file name="core" path="~/ajaxpro/core.ashx" />
- <file name="converter" path="~/ajaxpro/converter.ashx" />
- </scriptReplacements>
- -->
- <!-- <encryption cryptType="" keyType="" /> -->
- <!--
- Set the enabled attribute to true to enable the use of an Ajax.NET Professional
- token. This will send a token to the client that will be used to identify if the
- requests comes from the same PC.
- -->
- <token enabled="false" sitePassword="password" />
- <!--
- The oldStyle (or now configuration) section can be used to enable old styled JavaScript code or
- functions that are not used any more. Some of them cannot be used together.
- <configuration>
- <renderNotASPAJAXDateTime/>
- <objectExtendPrototype/>
- <appCodeQualifiedFullName/>
- <allowNumberBooleanAsString/>
- <sessionStateDefaultNone/>
- <includeMsPrototype/>
- <renderDateTimeAsString/>
- <noUtcTime/>
- <renderJsonCompliant/>
- <useSimpleObjectNaming/>
- </configuration>
- -->
- </ajaxSettings>
- </ajaxNet>
3)在webconfig —— <configuration>節(jié)點下,添加location節(jié)點,即如下代碼:
- <!--Ajax配置信息 C-->
- <location path="ajaxpro">
- <system.web>
- <httpHandlers>
- <add verb="*" path="*.ashx" type="AjaxPro.AjaxHandlerFactory,AjaxPro.2"/>
- </httpHandlers>
- <!--
- If you need to have Ajax.NET Professional methods running on the
- login page you may have to enable your own authorization configuration
- here.
- -->
- <!--
- <authorization>
- <deny users="?"/>
- </authorization>
- -->
- </system.web>
- </location>
4、注冊AjaxPro
導入AjaxPro命名空間,并在Page_Load事件處理中添加AjaxPro注冊代碼。
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using AjaxPro;
- namespace HujiangDict.Admin
- {
- public partial class Addword : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- //注冊AjaxPro,我的頁面是Addword.aspx,typeof中的類名就是Addword
- AjaxPro.Utility.RegisterTypeForAjax(typeof(Addword), this);
- }
- }
- }
5、編寫前臺代碼及客戶端方法
關(guān)鍵點是TextBox的onblur事件處理,調(diào)用的是 JS函數(shù) checkWord()。(我在這里添加了ASP.NET驗證控件和客戶端字符驗證的JS函數(shù),可以不考慮)
- <div class="title">
- 單 詞<asp:TextBox class="input_word" onblur="checkWord()" runat="server" ID="tb_word"
- onkeypress="return JudgeChar(event.keyCode)"></asp:TextBox><span class="message">
- <asp:RequiredFieldValidator ID="word_message" ControlToValidate="tb_word" runat="server"
- ErrorMessage="請輸入單詞" class="message"></asp:RequiredFieldValidator>
- </span>
- </div>
JS函數(shù),checkWord(),用于同后臺異步通信。該函數(shù)將服務(wù)器返回的結(jié)果,設(shè)置為id=msg消息框div的InnerHTML,即填充div,顯示出驗證信息。
- <!--Ajax檢查單詞是否存在-->
- <script type="text/javascript" language="javascript">
- function checkWord() {
- var word = document.getElementById('tb_word').value;
- if (word != '') {
- var result = HujiangDict.Admin.Addword.CheckWord(word).value;
- document.getElementById('msg').innerHTML = result;
- }
- }
- </script>
在JS調(diào)用后臺Ajax方法時,要參考頁面所繼承的類的完整名稱,這里是HujiangDict.Admin.Addword。
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Addword.aspx.cs" Inherits="HujiangDict.Admin.Addword" %> |
6、編寫服務(wù)端Ajax方法
后臺Ajax方法,要加上[AjaxMethod]標記,這是提供給前臺JS調(diào)用的方法。該方法類型為string類型,這里返回的結(jié)果是一段html,及顯示驗證結(jié)果的消息框。
- /// <summary>
- /// AjAx方法 檢查單詞是否存在
- /// </summary>
- /// <param name="word"></param>
- /// <returns></returns>
- [AjaxMethod]
- public string CheckWord(string word)
- {
- string result;
- WordHelper wordHelper = new WordHelper();
- //如果檢測數(shù)據(jù)庫中存在該單詞
- if (wordHelper.ExistsWord(word))
- {
- result = "<div style=\"background:#FFEBEB;border:solid 1px red;margin:10px 0;border-radius:6px;padding:0 20px\">" +
- "詞庫中已存在單詞 <strong>"+word+"</strong>,您可以到 <a href=\"#\">單詞管理</a> 中編輯該單詞。</div>";
- }
- else
- {
- result = "<div style=\"background:#BEFFD1;border:solid 1px green;margin:10px 0;border-radius:6px;padding:0 20px\">" +
- "數(shù)據(jù)庫中尚無該單詞 <strong>"+word+"</strong>,可以添加!^_^</div>";
- }
- return result;
- }
運行結(jié)果
添加一個單詞庫中不存在的單詞,鼠標離開編輯框時,提示“可以添加”。
添加單詞庫中已存在的單詞home時,提示“已存在”。
本文供剛學習Ajax的同學參考,高手請輕拍。AjaxPro現(xiàn)在已經(jīng)有點過時了,Ajax的實現(xiàn),目前比較流行的還是JQuery。但是多一種實現(xiàn)的方式,也就多一種思考的方式。 |
原文鏈接:http://www.cnblogs.com/libaoheng/archive/2012/04/10/2440573.html
【編輯推薦】