ASP 應用離不開 ActiveX 元件:資料庫存取、檔案系統、郵件發送、廣告輪播…皆須透過元件完成。本文建立 ActiveX 元件核心觀念,並以 AD Rotator 廣告輪播元件為例,示範從計劃檔、元件建立到頁面顯示的完整流程。
.dll 或 .exe),封裝一組可重用的物件、方法、屬性IDispatch 介面供腳本語言晚期繫結呼叫MSWC.AdRotator) 與 CLSIDSet MyAds = Server.CreateObject("MSWC.AdRotator")<OBJECT RUNAT=Server ID=MyAd PROGID="MSWC.AdRotator"></OBJECT>| 元件名稱 | ProgID | 主要功能 |
|---|---|---|
| Ad Rotator | MSWC.AdRotator | 依計劃檔輪播廣告圖片、追蹤曝光/點擊 |
| Browser Capabilities | MSWC.BrowserType | 偵測瀏覽器類型/版本/功能支援 |
| Database Access (ADO) | ADODB.Connection 等 | 資料庫存取核心 |
| Content Linking | MSWC.NextLink | 生成目錄導航、上一頁/下一頁連結 |
| File Access (FSO) | Scripting.FileSystemObject | 檔案/目錄讀寫、屬性查詢 |
| Collaboration Data Objects (CDONTS) | CDONTS.NewMail | SMTP 郵件發送 (Win2000/IIS5 內建) |
| MyInfo | MSWC.MyInfo | 站點管理員個人資訊儲存 |
| Counters | MSWC.Counters | 建立/遞增/讀取計數器 |
| Content Rotator | MSWC.ContentRotator | 輪播 HTML 內容字串 |
| Page Counter | MSWC.PageCounter | 頁面瀏覽計數顯示 |
REDIRECT /adclick.asp ; 點擊導向頁 (記錄點擊再轉向)
WIDTH 468
HEIGHT 60
BORDER 1
*
https://ads.example.com/banner1.gif 50 "廣告一" "https://www.ad1.com"
https://ads.example.com/banner2.gif 30 "廣告二" "https://www.ad2.com"
https://ads.example.com/banner3.gif 20 "廣告三" "https://www.ad3.com"
格式:圖片URL 權重(相對機率) "Alt文字" "點擊目標URL",權重總和不必為 100。
<%
' 記錄點擊日誌、統計...
Dim targetUrl
targetUrl = Request.QueryString("url")
If targetUrl <> "" Then Response.Redirect targetUrl
%>
<%@ Language=VBScript %>
<%
Set AdRot = Server.CreateObject("MSWC.AdRotator")
AdRot.Border = 1 ' 覆蓋計劃檔 BORDER 設定 (選用)
AdRot.TargetFrame = "_blank" ' 在新視窗開啟
%>
<html><body>
<h2>網站首頁</h2>
<div align="center">
<% Response.Write AdRot.GetAdvertisement("adrot.txt") %>
</div>
</body></html>
| 成員 | 類型 | 說明 |
|---|---|---|
| GetAdvertisement(scheduleFile) | 方法 | 回傳完整 <a><img></a> HTML 字串 |
| Border | 屬性 (讀寫) | 圖片邊框寬度,覆蓋計劃檔設定 |
| TargetFrame | 屬性 | 連結目標框架 (_blank, _top, _self) |
| Clickable | 屬性 | 是否產生超連結 (True/False) |
若需更靈活控制 (如依用戶畫像、地理位置、A/B 測試),可自行實作:
Function GetCustomAd(zoneId)
Dim conn, rs, sql, ads, i, rnd, totalWeight, pick
Set conn = GetDBConn()
sql = "SELECT ImageUrl, TargetUrl, AltText, Weight FROM Ads WHERE ZoneId=" & zoneId & " AND IsActive=1"
Set rs = conn.Execute(sql)
If rs.EOF Then GetCustomAd = "" : Exit Function
ads = rs.GetRows() ' 二維陣列
totalWeight = 0
For i = 0 To UBound(ads, 2)
totalWeight = totalWeight + ads(3, i)
Next
Randomize
pick = Int(Rnd * totalWeight) + 1
Dim cum : cum = 0
For i = 0 To UBound(ads, 2)
cum = cum + ads(3, i)
If pick <= cum Then
GetCustomAd = "" & _
"
"
Exit Function
End If
Next
End Function
ActiveX 元件是 ASP 擴充功能的基石。理解 Server.CreateObject、ProgID/CLSID、物件生命週期,並熟悉內建元件 (AD Rotator, BrowserCap, FSO, ADO, CDONTS) 的適用場景,即可快速組裝功能完整的 Web 應用。廣告輪播作為經典範例,展示了「資料驅動 + 元件渲染」的分離設計思想,值得在自訂元件開發中借鏡。