我们希望在使用Google API从servlet调用的浏览器上显示Google搜索结果的json。handleSearchResult未在浏览器上显示responseText。
此外,servlet没有将html文本框中的querywords映射到Google API search url(servlet)。谢谢
主页.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);
}
//.....
}

关于javascript - 在Web浏览器上显示JSON,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9786932/

10-09 20:07