XQuery/增量搜索
外观
< XQuery
您有一个大型数据集,并且希望使用 JavaScript 与服务器异步通信以在用户键入时缩小搜索范围。
美国大约有 43,000 个 5 位邮政编码。有很多应用程序可以将邮政编码转换为位置,例如 Ben Fry 的 使用 Processing 编写的 Java 小程序
此示例使用使用 Ajax 请求来自服务器端搜索的邮政编码 XML 数据库子集的客户端 XHTML 页面,并动态更新页面。
由 XQuery 生成,虽然内容是静态的。
declare option exist:serialize "method=xhtml media-type=text/html indent=yes";
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>ZIP Code to City and State using XmlHttpRequest</title>
<script language="javascript" src="ajaxzip.js"/>
</head>
<body>
<h1>US Zipcode decoder</h1>
<form onSubmit="getList(); return false">
<p>ZIP code:
<input type="text" size="5" name="zip" id="zip" onkeyup="getList();" onfocus="getList();" />
e.g. 95472
</p>
</form>
<div id="list"/>
</body>
</html>
使用 XMLHttpRequest 请求子集并使用 innerHTML 更新页面。
function updateList() {
if (http.readyState == 4) {
var divlist = document.getElementById('list');
divlist.innerHTML = http.responseText;
isWorking = false;
}
}
function getList() {
if (!isWorking && http) {
var zipcode = document.getElementById("zip").value;
http.open("GET", "getzip.xq?zipcode=" + escape(zipcode), true);
http.onreadystatechange = updateList;
// this sets the call-back function to be invoked when a response from the HTTP request is returned
isWorking = true;
http.send(null);
}
}
function getHTTPObject() {
var xmlhttp;
/*@cc_on
@if (@_jscript_version >= 5)
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
@else
xmlhttp = false;
@end @*/
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
try {
xmlhttp = new XMLHttpRequest();
xmlhttp.overrideMimeType("text/xml");
} catch (e) {
xmlhttp = false;
}
}
return xmlhttp;
}
var http = getHTTPObject(); // create the HTTP Object
var isWorking = false;
服务器端 XQuery 用于在 XML 数据库中执行搜索并生成 XHTML。这使用 eXist 全文索引和 exist 特定的 &= 运算符。
let $zipcode := request:get-parameter("zipcode",())
return
<div>
{if (string-length($zipcode) > 1) (: too slow :)
then
let $search := concat('^',$zipcode)
for $zip in //Zipcode[matches(Code,$search)]
return
<div>{string-join(($zip/Code,$zip/Area,$zip/State),' ')}</div>
else ()
}
</div>
数据最初是 CSV 文件,使用 Excel 和 XML 加载项转换为 XML。这是数据样本。
<Zipcodes>
<Zipcode>
<Code>210</Code>
<Area>Portsmouth</Area>
<State>NH</State>
</Zipcode>
<Zipcode>
<Code>211</Code>
<Area>Portsmouth</Area>
<State>NH</State>
</Zipcode>
<Zipcode>
<Code>212</Code>
<Area>Portsmouth</Area>
<State>NH</State>
</Zipcode>
<Zipcode>
<Code>213</Code>
<Area>Portsmouth</Area>
<State>NH</State>
</Zipcode>
...