本文采用Ajax访问Yahoo!的Web服务,实现效果与<<Ajax基础教程>>中的4.8一样,但书中是用JAVA写的服务器代码,这里我用.NET重写,客户端代码如下:
<!
DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
>
< html xmlns ="http://www.w3.org/1999/xhtml" >
< head >
< title > Yahoo! Search Web Services </ title >
< script type ="text/javascript" > ...
var xmlHttp;
function createXMLHttpRequest() ...{
if (window.ActiveXObject) ...{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest) ...{
xmlHttp = new XMLHttpRequest();
}
}
function doSearch() ...{
var url = "YahooSearchGateway.aspx?" + createQueryString() + "&ts=" + new Date().getTime();
createXMLHttpRequest();
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
function createQueryString() ...{
var searchString = document.getElementById("searchString").value;
searchString = escape(searchString);
var maxResultsCount = document.getElementById("maxResultCount").value;
var queryString = "query=" + searchString + "&results=" + maxResultsCount;
return queryString;
}
function handleStateChange() ...{
if(xmlHttp.readyState == 4) ...{
if(xmlHttp.status == 200) ...{
parseSearchResults();
}
else ...{
alert("Error accessing Yahoo! search");
}
}
}
function parseSearchResults() ...{
var resultsDiv = document.getElementById("results");
while(resultsDiv.childNodes.length > 0) ...{
resultsDiv.removeChild(resultsDiv.childNodes[0]);
}
var allResults = xmlHttp.responseXML.getElementsByTagName("Result");
var result = null;
for(var i = 0; i < allResults.length; i++) ...{
result = allResults[i];
parseResult(result);
}
}
function parseResult(result) ...{
var resultDiv = document.createElement("div");
var title = document.createElement("h3");
title.appendChild(document.createTextNode(getChildElementText(result, "Title")));
resultDiv.appendChild(title);
var summary = document.createTextNode(getChildElementText(result, "Summary"));
resultDiv.appendChild(summary);
resultDiv.appendChild(document.createElement("br"));
var clickHere = document.createElement("a");
clickHere.setAttribute("href", getChildElementText(result, "ClickUrl"));
clickHere.appendChild(document.createTextNode(getChildElementText(result, "Url")));
resultDiv.appendChild(clickHere);
document.getElementById("results").appendChild(resultDiv);
}
function getChildElementText(parentNode, childTagName) ...{
var childTag = parentNode.getElementsByTagName(childTagName);
return childTag[0].firstChild.nodeValue;
}
</ script >
</ head >
< body >
< h1 >
Web Search Using Yahoo! Search Web Services </ h1 >
< form action ="#" >
Search String:
< input type ="text" id ="searchString" />
< br />
< br />
Max Number of Results:
< select id ="maxResultCount" >
< option value ="1" > 1 </ option >
< option value ="10" > 10 </ option >
< option value ="25" > 25 </ option >
< option value ="50" > 50 </ option >
</ select >
< br />
< br />
< input type ="button" value ="Submit" onclick ="doSearch();" />
</ form >
< h2 >
Results: </ h2 >
< div id ="results" />
</ body >
</ html >
< html xmlns ="http://www.w3.org/1999/xhtml" >
< head >
< title > Yahoo! Search Web Services </ title >
< script type ="text/javascript" > ...
var xmlHttp;
function createXMLHttpRequest() ...{
if (window.ActiveXObject) ...{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest) ...{
xmlHttp = new XMLHttpRequest();
}
}
function doSearch() ...{
var url = "YahooSearchGateway.aspx?" + createQueryString() + "&ts=" + new Date().getTime();
createXMLHttpRequest();
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
function createQueryString() ...{
var searchString = document.getElementById("searchString").value;
searchString = escape(searchString);
var maxResultsCount = document.getElementById("maxResultCount").value;
var queryString = "query=" + searchString + "&results=" + maxResultsCount;
return queryString;
}
function handleStateChange() ...{
if(xmlHttp.readyState == 4) ...{
if(xmlHttp.status == 200) ...{
parseSearchResults();
}
else ...{
alert("Error accessing Yahoo! search");
}
}
}
function parseSearchResults() ...{
var resultsDiv = document.getElementById("results");
while(resultsDiv.childNodes.length > 0) ...{
resultsDiv.removeChild(resultsDiv.childNodes[0]);
}
var allResults = xmlHttp.responseXML.getElementsByTagName("Result");
var result = null;
for(var i = 0; i < allResults.length; i++) ...{
result = allResults[i];
parseResult(result);
}
}
function parseResult(result) ...{
var resultDiv = document.createElement("div");
var title = document.createElement("h3");
title.appendChild(document.createTextNode(getChildElementText(result, "Title")));
resultDiv.appendChild(title);
var summary = document.createTextNode(getChildElementText(result, "Summary"));
resultDiv.appendChild(summary);
resultDiv.appendChild(document.createElement("br"));
var clickHere = document.createElement("a");
clickHere.setAttribute("href", getChildElementText(result, "ClickUrl"));
clickHere.appendChild(document.createTextNode(getChildElementText(result, "Url")));
resultDiv.appendChild(clickHere);
document.getElementById("results").appendChild(resultDiv);
}
function getChildElementText(parentNode, childTagName) ...{
var childTag = parentNode.getElementsByTagName(childTagName);
return childTag[0].firstChild.nodeValue;
}
</ script >
</ head >
< body >
< h1 >
Web Search Using Yahoo! Search Web Services </ h1 >
< form action ="#" >
Search String:
< input type ="text" id ="searchString" />
< br />
< br />
Max Number of Results:
< select id ="maxResultCount" >
< option value ="1" > 1 </ option >
< option value ="10" > 10 </ option >
< option value ="25" > 25 </ option >
< option value ="50" > 50 </ option >
</ select >
< br />
< br />
< input type ="button" value ="Submit" onclick ="doSearch();" />
</ form >
< h2 >
Results: </ h2 >
< div id ="results" />
</ body >
</ html >
在按下Submit按钮时,客户端调用doSearch()函数,构造QueryString查询字符串,生成XmlHttpRequest,并设callback函数,open后,send,其中query和results参数都是yahoo! search web services内设的参数,此时向服务器端发出异步调用,下面先看看服务器端的代码:
protected
void
Page_Load(
object
sender, EventArgs e)
... {
string url = "http://api.search.yahoo.com/WebSearchService/V1/webSearch?appid=your_app_id&type=all&"+this.Request.Url.Query.Substring(1);
HttpWebRequest hwr = WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response = hwr.GetResponse() as HttpWebResponse)
...{
StreamReader sr = new StreamReader(response.GetResponseStream());
this.Response.ContentType = "text/xml";
this.Response.Write(sr.ReadToEnd());
this.Response.Flush();
this.Response.Close();
}
}
... {
string url = "http://api.search.yahoo.com/WebSearchService/V1/webSearch?appid=your_app_id&type=all&"+this.Request.Url.Query.Substring(1);
HttpWebRequest hwr = WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response = hwr.GetResponse() as HttpWebResponse)
...{
StreamReader sr = new StreamReader(response.GetResponseStream());
this.Response.ContentType = "text/xml";
this.Response.Write(sr.ReadToEnd());
this.Response.Flush();
this.Response.Close();
}
}
通过WebRequest.Create创建请求,再GetResponse,通过GetResponseStream获得响应的内容,再用this.Response.Write方法写入流中,最后刷新,关闭,还要记得设置ContentType,让响应以xml方式发出,在客户端会得到一个xml document,用xmlHttp.responseXML可以获得。
这个xml document中有title,summary,url,clickurl等tag,用相应的javascript dom可以获得,最后就是一些显示处理问题了。