在.NET中結合AJAX調用Yahoo! Search Web Services

本文采用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>

 在按下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();
        }

    }

通過WebRequest.Create創建請求,再GetResponse,通過GetResponseStream獲得響應的內容,再用this.Response.Write方法寫入流中,最後刷新,關閉,還要記得設置ContentType,讓響應以xml方式發出,在客戶端會得到一個xml document,用xmlHttp.responseXML可以獲得。

這個xml document中有title,summary,url,clickurl等tag,用相應的javascript dom可以獲得,最後就是一些顯示處理問題了。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章