萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML 腳本教學

ASP.NET AJAX 擴充 HTML Map 控制項:熱點點擊局部更新無刷新體驗

專案背景

ASP.NET 2.0 內建 ImageMap 控制項支援熱點回發,但會導致整頁重新整理。本文示範以 ASP.NET AJAX 框架擴充原生 HTML <map><area>,實現熱點點擊時僅局部更新,符合 Web 2.0 體驗。

前端 HTML 結構

<img src="images/solarsys.gif" width="504" height="126" border="0" alt="Solar System" usemap="#SystemMap">
<map name="SystemMap">
  <area shape="rect" coords="0,0,82,126" onmouseover="GetAreaInfo(event, 'sun');" onmouseout="HidePopup();">
  <area shape="circle" coords="90,58,3" onmouseover="GetAreaInfo(event, 'merglobe');" onmouseout="HidePopup();">
  ...
</map>
  • onmouseover:滑鼠進入顯示彈出資訊
  • onmouseout:滑鼠離開隱藏彈出資訊

後端 AJAX Web Service

[ScriptService]
public class LocationService : System.Web.Services.WebService {
    [WebMethod]
    [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
    public string GetAreaInfo(string area) {
        // 實際應用:從資料庫查詢 area 詳細資料
        return area; // 示範直接回傳
    }
}

ScriptManager 註冊服務

<asp:ScriptManager ID="ScriptManager1" runat="server">
  <Services>
    <asp:ServiceReference Path="~/LocationService.asmx" />
  </Services>
</asp:ScriptManager>

此設定會產生 <script src="LocationService.asmx/jsdebug">,建立客戶端 Proxy 類別。

客戶端 JavaScript 類別 (ImageMap.js)

Type.registerNamespace("MyServices");

MyServices.Location = function(uiElement, uiBody) {
    MyServices.Location.initializeBase(this);
    this._uiElement = uiElement;
    this._uiBody = uiBody;
    this._xAxis = 0;
    this._yAxis = 0;
}

MyServices.Location.prototype = {
    get_uiElement: function() { return this._uiElement; },
    set_uiElement: function(value) { this._uiElement = value; },
    get_uiBody: function() { return this._uiBody; },
    set_uiBody: function(value) { this._uiBody = value; },

    ShowPopupInfo: function(event, areaName) {
        MyServices.LocationService.GetAreaInfo(areaName,
            Function.createDelegate(this, this.OnCompleted),
            this.OnError,
            this.OnTimeOut);
        this._xAxis = event.clientX;
        this._yAxis = event.clientY;
    },
    // OnCompleted, OnError, OnTimeOut 實作略...
}

MyServices.Location.registerClass('MyServices.Location', Sys.UI.Control);

關鍵技術點

  • Function.createDelegate:解決非同步回呼中 this 指向問題
  • JSON 回傳格式,輕量高效
  • HTTP POST 呼叫,安全性較佳
  • 彈出視窗定位使用 event.clientX/Y

AJAX Map 熱點彈出示例

copyright © 萬盛學電腦網 all rights reserved