我们希望使用Google API在从servlet调用的浏览器上显示Google搜索结果的json。handleSearchResult
未在浏览器上显示responseText。另外,servlet没有将查询词从html的文本框映射到Google API搜索url(servlet)。感谢
home.html
<html>
<head>
<script type="text/javascript">
var request;
function handleSearchResult(){
alert("hanldeRes");
//query.text = resp.items.name;
alert(request.responseText);
//var resp = eval('('+responseText+')');
//alert(resp.items.title);
}
function createHttpRequest()
{
alert("insideCreateRequest");
if(typeof XMLHttpRequest != "undefined") {
request = new XMLHttpRequest();
}
else if(window.ActiveXObject) {
request = new ActiveXObject("Msxml2.XMLHTTP");
if(!request) {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
}
if(request) {
request.onreadystatechange = handleSearchResult();
request.open("GET","http://localhost:8080/WebSearchOptimization/SearchService",true);
request.send(null);
}
else {
alert("error on Page createHttpRequest");
}
return false;
}
function home_onclick()
{
alert("passingRequest");
createHttpRequest();
}
</script>
</head>
<body>
<br><br>
<form method="get" name="form">
<input type="text" id="query" name="query">
<input type="button" value="Search" id="search" onclick="home_onclick()">
<div></div>
</form>
</body>
</html>
我对您的代码进行了一些修改。希望这会有所帮助。
function handleSearchResult(){
if (request.readyState==4 && request.status==200)
{
alert(request.responseText);
}
}
function createHttpRequest()
{
//....
if(request) {
request.onreadystatechange = handleSearchResult;
var q = encodeURI( document.getElementById("query").value );
request.open("GET","http://localhost:8080/WebSearchOptimization/SearchService?"+q,true);
request.send(null);
}
//.....
}