先看一段示範:把 XML 中的公制身高轉成英制,再印出整份文件。
for each (var p in x.person) {
if (p.height.@measure == "metric")
p.height = metricToImperial(p.height);
}
print(x);
輸出結果:
<people>
<person gender="male">
<name>Ant</name>
<hair>Shaggy</hair>
<eyes>Blue</eyes>
<height measure="imperial">
<feet>5</feet>
<inches>11</inches>
</height>
</person>
<person gender="male">
<name>Paul</name>
<hair>Spiky</hair>
<eyes>Grey</eyes>
<height measure="imperial">
<feet>5</feet>
<inches>12</inches>
</height>
</person>
</people>
熟悉 XML 的人此時會想知道命名空間怎麼處理。E4X 提供了三種方式。
第一,在字面 XML 中直接宣告:
var soapMsg = <s:Envelope xmlns:s="https://www.w3.org/2003/05/soap-envelope"/>; print(soapMsg.namespace()); // https://www.w3.org/2003/05/soap-envelope
第二,在建立元素之前設定預設命名空間:
default xml namespace = new Namespace("https://www.w3.org/2003/05/soap-envelope");
要重設回無命名空間,把它設為空字串即可:
default xml namespace = ""
第三,使用 :: 運算子:
var f = new Namespace("https://fremantle.org");
soapMsg.Body.f::GetStockQuote = "IBM";
print(soapMsg);
<s:Envelope xmlns:s="https://www.w3.org/2003/05/soap-envelope">
<s:Body>
<frem:GetStockQuote xmlns:frem="https://fremantle.org">
IBM
</frem:GetStockQuote>
</s:Body>
</s:Envelope>
E4X 一個明顯的優點是它完整支援 XML,包含排序(ordering)。許多「XML 文件映射到程式語言物件」的方案只支援符合物件語義的 XML 子集,因此失去了同時表示物件與文件的能力。E4X 的 XML 物件內建了對元素順序做細緻控制的功能,這一點在處理 SOAP 這類對元素順序敏感的協定時尤其重要。
最後一項基礎語法是花括號 {}。E4X 允許你在字面 XML 中重新回到 JavaScript 環境,插入計算後的運算結果:
var num = 36;
var p = <paul><age>{num}</age></paul>;
print(p);
<paul> <age>36</age> </paul>
接下來示範兩種環境:使用 XMLHttpRequest 的 Mozilla 1.8,以及 Java/Rhino。
在瀏覽器中用 E4X 呼叫 Web 服務其實很容易,但有個前提:當時唯一支援 E4X 的瀏覽器是 Mozilla 1.8。這並不是一個可攜的跨瀏覽器方案,以下範例只是為了展示 E4X 能以多簡潔的方式完成這件事。
樣本 stockclient.html 向 SOAP 伺服器送出並接收 SOAP 訊息,靠的是 XMLHttpRequest 物件——它讓跑在瀏覽器內的腳本能在後台發出 HTTP 請求,Google 的 GMail 之所以能做到那些事,背後就是這個機制。這種架構後來被命名為 Asynchronous JavaScript + XML(Ajax)。
從根本上看,Ajax 的目的是以更靈活的方式與伺服器互動,取代標準 HTML/HTTP 的「頁面」模型,藉此提升 Web 頁面的反應能力與可用性。Google Maps beta 是很好的示範,它明顯比過去的地圖站點更具互動性。
示範中使用的是 xmethods.net 上的標準 Web 服務。但這裡有個障礙:瀏覽器的安全性規則一般不允许腳本或 Java applet 建立連到「非產生該頁面的伺服器」的網路連線。否則你需要一個代理頁,把請求「複製」到另一台伺服器上。
範例中為繞過這個限制採取了兩步:先在 Mozilla 設定中把 signed.applets.codebase_principal_support 從 false 改為 true,再在腳本中請求提升權限:
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect UniversalBrowserAccess");
更恰當的替代方案是把服務與頁面部署在同一個 Web 應用伺服器(如 WebSphere 或 Tomcat)下——Apache Axis 及其內建的股票報價範例就是這種做法。
首先宣告要使用的 E4X:
<script type="text/javascript;e4x=1">
按下 Send 之後,腳本先建立 SOAP 信封:
var s = new Namespace("s", "https://schemas.xmlsoap.org/soap/envelope/");
var envelope = <s:Envelope xmlns:s={s}/>;
envelope.s::Body = "";
var body = envelope.s::Body;
這對任何 SOAP 請求都通用:建立一個不含訊息體的信封。等價的字面寫法是:
var envelope = <s:Envelope xmlns:s="https://schemas.xmlsoap.org/soap/envelope/"> <s:Body/> </s:Envelope>
但前面的写法更省事,而且順手拿到了指向 Body 的參照。
接著建立訊息主體:
var x = new Namespace("x", "urn:xmethods-delayed-quotes");
body.x::getQuote = <x:getQuote xmlns:x={x}/>;
var symbol = document.getElementById("symbol").value;
var getQuote = body.x::getQuote;
getQuote.symbol = symbol;
此時你已經有一則完整的 SOAP 請求訊息:
<s:Envelope xmlns:s="https://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<x:getQuote xmlns:x="urn:xmethods-delayed-quotes">
<symbol>XXX</symbol>
</x:getQuote>
</s:Body>
</s:Envelope>
要把它送出去,需要 XMLHttpRequest。我們寫了一個輔助函數 execService,同時支援同步與非同步兩種呼叫方式:
function execService(url, XML, callback) {
var xmlhttp = new XMLHttpRequest();
var async = false;
if (arguments.length == 3) async = true;
xmlhttp.open("POST", url, async);
xmlhttp.setRequestHeader("SOAPAction", "\"\"");
xmlhttp.setRequestHeader("Content-Type", "text/xml");
if (async) {
var f = function() {
if (xmlhttp.readyState == 4) {
callback(new XML(xmlhttp.responseText));
}
}
xmlhttp.onreadystatechange = f;
}
xmlhttp.send(XML.toString());
if (!async) return new XML(xmlhttp.responseText);
}
它支援兩種呼叫形式:
XML execService(String url, XML envelope); void execService(String url, XML envelope, function callback);
回呼函數的簽章是 void callback(XML x)。函數依參數個數判斷模式(三個參數即非同步),然後用 XMLHttpRequest 以 POST 把 XML 訊息放進請求並送到指定 URL。