Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/89.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Google自定义搜索JSON API在调用时不断刷新_Javascript_Html_Google Api_Google Custom Search - Fatal编程技术网

Javascript Google自定义搜索JSON API在调用时不断刷新

Javascript Google自定义搜索JSON API在调用时不断刷新,javascript,html,google-api,google-custom-search,Javascript,Html,Google Api,Google Custom Search,出于某种原因,当我使用下面的代码在一个网站上搜索一个术语时,我已经设置了一个谷歌自定义搜索引擎,它会无限刷新,我相信代码中有一些我无法捕捉到的bug。我从另一个stackoverflow答案中找到了代码,我在这里尝试的是获取每个搜索查询返回的JSON数据,并将其显示为与普通google搜索结果类似的设计 Search.html <!DOCTYPE html> <html> <head> <title></title> </

出于某种原因,当我使用下面的代码在一个网站上搜索一个术语时,我已经设置了一个谷歌自定义搜索引擎,它会无限刷新,我相信代码中有一些我无法捕捉到的bug。我从另一个stackoverflow答案中找到了代码,我在这里尝试的是获取每个搜索查询返回的JSON数据,并将其显示为与普通google搜索结果类似的设计

Search.html

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <form action="results.html" id="cse-search-box">
        <div>
            <input class="" name="q" type="text"> 
            <input class="" type="submit">
        </div>
    </form>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <title>JSON Custom Search API</title>

    <style type="text/css">
        body{
            width: 100%;
        }
        .gs-image{
            max-width: 100px;
        }
    </style>
</head>
<body>
    <h2 style="font-weight: bold; ">Search Results:</h2>
    <div class="gsc-result-info" id="resInfo-0"></div>
    <hr/>
    <div id="googleContent"></div>

    <script>
    //Handler for response from google.
    function hndlr(response) {
        if (response.items == null) {
            //Sometimes the results say there are 34 results/4 pages, but when you click through to 3 then there is only 30, so page 4 is invalid now.
            //So if we get to the invalid one, send them back a page.
            window.location.replace("results.html?start=" + (start - 10) + "&q=" + query);
            return;
        }
        //Search results load time
        document.getElementById("resInfo-0").innerHTML = "About " + response.searchInformation.formattedTotalResults + " results (" + response.searchInformation.formattedSearchTime + " seconds)";
        //Clear the div first, CMS is inserting a space for some reason.
        document.getElementById("googleContent").innerHTML = "";
        //Loop through each item in search results
        for (var i = 0; i < response.items.length; i++) {
            var item = response.items[i];
            var content = "";

            content += "<div class='gs-webResult gs-result'>" +
            "<table class='gsc-table-result'><tbody><tr>";
            //Thumbnail image
            // if (item.pagemap.cse_thumbnail != null)
            //     content += "<td class='gsc-table-cell-thumbnail gsc-thumbnail'><div class='gs-image-box gs-web-image-box gs-web-image-box-portrait'><a class='gs-image' href='" + item.link + "'>" +
            // "<img class='gs-image' class = 'gs-image-box gs-web-image-box gs-web-image-box-portrait' src='" + item.pagemap.cse_thumbnail[0].src + "'></a></td>";
            //Link
            content += "<td><a class='gs-title' href='" + item.link + "'>" + item.htmlTitle + "</a><br/>";
            //File format for PDF, etc.
            if (item.fileFormat != null)
                content += "<div class='gs-fileFormat'><span class='gs-fileFormat'>File Format: </span><span class='gs-fileFormatType'>" + item.fileFormat + "</span></div>";
            //description text and URL text.
            content += item.htmlSnippet.replace('<br>','') + "<br/><div class='gs-bidi-start-align gs-visibleUrl gs-visibleUrl-long' dir='ltr' style='word-break:break-all;'>" + item.htmlFormattedUrl +"</div>" +
            "<br/></td></tr></tbody></table></div>";
            document.getElementById("googleContent").innerHTML += content;
        }
        //Page Controls
        var totalPages = Math.ceil(response.searchInformation.totalResults / 10);
        var currentPage = Math.floor(start / 10 + 1);
        var pageControls = "<div class='gsc-results'><div class='gsc-cursor-box gs-bidi-start-align' dir='ltr'><div class='gsc-cursor'>";
        //Page change controls, 10 max.
        for (var x = 1; x <= totalPages && x<=10; x++) {
            pageControls += "<span class='gsc-cursor-page";
            if (x === currentPage)
                pageControls += "gsc-cursor-current-page";
            var pageLinkStart = x * 10 - 9;
            pageControls+="'><a href='results.html?start="+pageLinkStart+"&q="+query+"'>"+x+"</a>&nbsp;&nbsp;</span>";
        }
        pageControls += "</div></div></div>";
        document.getElementById("googleContent").innerHTML += pageControls;
    }

    //Get search text from query string.a
    var query = document.URL.substr(document.URL.indexOf("q=") + 2);
    var start = document.URL.substr(document.URL.indexOf("start=") + 6, 2);
    if (start === "1&" || document.URL.indexOf("start=") === -1)
        start = 1;

    //Load the script src dynamically to load script with query to call.
    //DOM: Create the script element
    var jsElm = document.createElement("script");
    //Set the type attribute
    jsElm.type = "application/javascript";
    //Make the script element load file
    jsElm.src = "https://www.googleapis.com/customsearch/v1?key=yourAPIkeyHERE&cx=yourSEARCHengineIDhere&start="+start+"&q=" +query +"&callback=hndlr";
    //Finally insert the element to the body element in order to load the script
    document.body.appendChild(jsElm);
</script>
</body>
</html>

Results.html

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <form action="results.html" id="cse-search-box">
        <div>
            <input class="" name="q" type="text"> 
            <input class="" type="submit">
        </div>
    </form>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <title>JSON Custom Search API</title>

    <style type="text/css">
        body{
            width: 100%;
        }
        .gs-image{
            max-width: 100px;
        }
    </style>
</head>
<body>
    <h2 style="font-weight: bold; ">Search Results:</h2>
    <div class="gsc-result-info" id="resInfo-0"></div>
    <hr/>
    <div id="googleContent"></div>

    <script>
    //Handler for response from google.
    function hndlr(response) {
        if (response.items == null) {
            //Sometimes the results say there are 34 results/4 pages, but when you click through to 3 then there is only 30, so page 4 is invalid now.
            //So if we get to the invalid one, send them back a page.
            window.location.replace("results.html?start=" + (start - 10) + "&q=" + query);
            return;
        }
        //Search results load time
        document.getElementById("resInfo-0").innerHTML = "About " + response.searchInformation.formattedTotalResults + " results (" + response.searchInformation.formattedSearchTime + " seconds)";
        //Clear the div first, CMS is inserting a space for some reason.
        document.getElementById("googleContent").innerHTML = "";
        //Loop through each item in search results
        for (var i = 0; i < response.items.length; i++) {
            var item = response.items[i];
            var content = "";

            content += "<div class='gs-webResult gs-result'>" +
            "<table class='gsc-table-result'><tbody><tr>";
            //Thumbnail image
            // if (item.pagemap.cse_thumbnail != null)
            //     content += "<td class='gsc-table-cell-thumbnail gsc-thumbnail'><div class='gs-image-box gs-web-image-box gs-web-image-box-portrait'><a class='gs-image' href='" + item.link + "'>" +
            // "<img class='gs-image' class = 'gs-image-box gs-web-image-box gs-web-image-box-portrait' src='" + item.pagemap.cse_thumbnail[0].src + "'></a></td>";
            //Link
            content += "<td><a class='gs-title' href='" + item.link + "'>" + item.htmlTitle + "</a><br/>";
            //File format for PDF, etc.
            if (item.fileFormat != null)
                content += "<div class='gs-fileFormat'><span class='gs-fileFormat'>File Format: </span><span class='gs-fileFormatType'>" + item.fileFormat + "</span></div>";
            //description text and URL text.
            content += item.htmlSnippet.replace('<br>','') + "<br/><div class='gs-bidi-start-align gs-visibleUrl gs-visibleUrl-long' dir='ltr' style='word-break:break-all;'>" + item.htmlFormattedUrl +"</div>" +
            "<br/></td></tr></tbody></table></div>";
            document.getElementById("googleContent").innerHTML += content;
        }
        //Page Controls
        var totalPages = Math.ceil(response.searchInformation.totalResults / 10);
        var currentPage = Math.floor(start / 10 + 1);
        var pageControls = "<div class='gsc-results'><div class='gsc-cursor-box gs-bidi-start-align' dir='ltr'><div class='gsc-cursor'>";
        //Page change controls, 10 max.
        for (var x = 1; x <= totalPages && x<=10; x++) {
            pageControls += "<span class='gsc-cursor-page";
            if (x === currentPage)
                pageControls += "gsc-cursor-current-page";
            var pageLinkStart = x * 10 - 9;
            pageControls+="'><a href='results.html?start="+pageLinkStart+"&q="+query+"'>"+x+"</a>&nbsp;&nbsp;</span>";
        }
        pageControls += "</div></div></div>";
        document.getElementById("googleContent").innerHTML += pageControls;
    }

    //Get search text from query string.a
    var query = document.URL.substr(document.URL.indexOf("q=") + 2);
    var start = document.URL.substr(document.URL.indexOf("start=") + 6, 2);
    if (start === "1&" || document.URL.indexOf("start=") === -1)
        start = 1;

    //Load the script src dynamically to load script with query to call.
    //DOM: Create the script element
    var jsElm = document.createElement("script");
    //Set the type attribute
    jsElm.type = "application/javascript";
    //Make the script element load file
    jsElm.src = "https://www.googleapis.com/customsearch/v1?key=yourAPIkeyHERE&cx=yourSEARCHengineIDhere&start="+start+"&q=" +query +"&callback=hndlr";
    //Finally insert the element to the body element in order to load the script
    document.body.appendChild(jsElm);
</script>
</body>
</html>

JSON自定义搜索API
身体{
宽度:100%;
}
.gs图像{
最大宽度:100px;
}
搜索结果:

//处理来自google的响应。 hndlr职能(响应){ if(response.items==null){ //有时结果显示有34个结果/4页,但当你点击到3页时,只有30个,因此第4页现在无效。 //因此,如果我们找到了无效的一个,就把它们发回一页。 window.location.replace(“results.html?start=“+(start-10)+”&q=“+query”); 返回; } //搜索结果加载时间 document.getElementById(“resInfo-0”).innerHTML=“关于”+response.searchInformation.formattedTotalResults+”结果(“+response.searchInformation.formattedSearchTime+”秒)”; //首先清除div,CMS出于某种原因正在插入空格。 document.getElementById(“谷歌内容”).innerHTML=“”; //循环搜索结果中的每个项目 对于(var i=0;i”; //PDF等的文件格式。 如果(item.fileFormat!=null) content+=“文件格式:”+item.fileFormat+”; //说明文本和URL文本。 content+=item.htmlSnippet.replace(“
”,“)+”
“+item.htmlFormattedUrl+”+ “
”; document.getElementById(“googleContent”).innerHTML+=content; } //页面控件 var totalPages=Math.ceil(response.searchInformation.totalResults/10); var currentPage=数学楼层(开始/10+1); var pageControls=“”; //页面更改控件,最多10个。
对于(var x=1;x我已将您的代码尝试到我的本地环境中。我在谷歌搜索中收到了这个错误

hndlr
当响应为null时,此函数会反复调用页面,对吗?因此,由于
API键
响应对象返回错误,所以页面会不断刷新

如果您提供了正确的
API密钥
,则google返回响应,页面无法刷新,因为您对其设置了如下条件:

response.items === null
我们可以再次管理更多的条件,通过向其中添加一个条件来防止递归性

我在
hndlr
功能中的代码中更新了一个条件:

<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <title>JSON Custom Search API</title>

    <style type="text/css">
        body {
            width: 100%;
        }

        .gs-image {
            max-width: 100px;
        }
    </style>
</head>

<body>
    <h2 style="font-weight: bold; ">Search Results:</h2>
    <div class="gsc-result-info" id="resInfo-0"></div>
    <hr />
    <div id="googleContent"></div>

    <script>
        //Handler for response from google.
        function hndlr(response) {
            console.log(response);
            if (response.items == null && !response.error) {

                //Sometimes the results say there are 34 results/4 pages, but when you click through to 3 then there is only 30, so page 4 is invalid now.
                //So if we get to the invalid one, send them back a page.
                window.location.replace("customsearch.html?start=" + (start - 10) + "&q=" + query);
                return;
            }
            //Search results load time
            document.getElementById("resInfo-0").innerHTML = "About " + response.searchInformation.formattedTotalResults + " results (" + response.searchInformation.formattedSearchTime + " seconds)";
            //Clear the div first, CMS is inserting a space for some reason.
            document.getElementById("googleContent").innerHTML = "";
            //Loop through each item in search results
            for (var i = 0; i < response.items.length; i++) {
                var item = response.items[i];
                var content = "";

                content += "<div class='gs-webResult gs-result'>" +
                    "<table class='gsc-table-result'><tbody><tr>";
                //Thumbnail image
                // if (item.pagemap.cse_thumbnail != null)
                //     content += "<td class='gsc-table-cell-thumbnail gsc-thumbnail'><div class='gs-image-box gs-web-image-box gs-web-image-box-portrait'><a class='gs-image' href='" + item.link + "'>" +
                // "<img class='gs-image' class = 'gs-image-box gs-web-image-box gs-web-image-box-portrait' src='" + item.pagemap.cse_thumbnail[0].src + "'></a></td>";
                //Link
                content += "<td><a class='gs-title' href='" + item.link + "'>" + item.htmlTitle + "</a><br/>";
                //File format for PDF, etc.
                if (item.fileFormat != null)
                    content += "<div class='gs-fileFormat'><span class='gs-fileFormat'>File Format: </span><span class='gs-fileFormatType'>" + item.fileFormat + "</span></div>";
                //description text and URL text.
                content += item.htmlSnippet.replace('<br>', '') + "<br/><div class='gs-bidi-start-align gs-visibleUrl gs-visibleUrl-long' dir='ltr' style='word-break:break-all;'>" + item.htmlFormattedUrl + "</div>" +
                    "<br/></td></tr></tbody></table></div>";
                document.getElementById("googleContent").innerHTML += content;
            }
            //Page Controls
            var totalPages = Math.ceil(response.searchInformation.totalResults / 10);
            var currentPage = Math.floor(start / 10 + 1);
            var pageControls = "<div class='gsc-results'><div class='gsc-cursor-box gs-bidi-start-align' dir='ltr'><div class='gsc-cursor'>";
            //Page change controls, 10 max.
            for (var x = 1; x <= totalPages && x <= 10; x++) {
                pageControls += "<span class='gsc-cursor-page";
                if (x === currentPage)
                    pageControls += "gsc-cursor-current-page";
                var pageLinkStart = x * 10 - 9;
                pageControls += "'><a href='customsearch.html?start=" + pageLinkStart + "&q=" + query + "'>" + x + "</a>&nbsp;&nbsp;</span>";
            }
            pageControls += "</div></div></div>";
            document.getElementById("googleContent").innerHTML += pageControls;
        }

        //Get search text from query string.a
        var query =  document.URL.substr(document.URL.indexOf("q=") + 2);
        var start = document.URL.substr(document.URL.indexOf("start=") + 6, 2);
        if (start === "1&" || document.URL.indexOf("start=") === -1)
            start = 1;

        //Load the script src dynamically to load script with query to call.
        //DOM: Create the script element
        var jsElm = document.createElement("script");
        //Set the type attribute
        jsElm.type = "application/javascript";
        //Make the script element load file
        jsElm.src = "https://www.googleapis.com/customsearch/v1?key=yourAPIkeyHERE&cx=yourSEARCHengineIDhere&start=" + start + "&q=" + query + "&callback=hndlr";
        //Finally insert the element to the body element in order to load the script
        document.body.appendChild(jsElm);
    </script>
</body>

</html>

JSON自定义搜索API
身体{
宽度:100%;
}
.gs图像{
最大宽度:100px;
}
搜索结果:

//处理来自google的响应。 hndlr职能(响应){ 控制台日志(响应); if(response.items==null&&!response.error){ //有时结果显示有34个结果/4页,但当你点击到3页时,只有30个,因此第4页现在无效。 //因此,如果我们找到了无效的一个,就把它们发回一页。 window.location.replace(“customsearch.html?start=“+(start-10)+”&q=“+query”); 返回; } //搜索结果加载时间 document.getElementById(“resInfo-0”).innerHTML=“关于”+response.searchInformation.formattedTotalResults+”结果(“+response.searchInformation.formattedSearchTime+”秒)”; //首先清除div,CMS出于某种原因正在插入空格。 document.getElementById(“谷歌内容”).innerHTML=“”; //循环搜索结果中的每个项目 对于(var i=0;i”; //PDF等的文件格式。 如果(item.fileFormat!=null) content+=“文件格式:”+item.fileFormat+”; //说明文本和URL文本。 content+=item.htmlSnippet.replace(“
”,“)+”
“+item.htmlFormattedUrl+”+ “
”; document.getElementById(“googleContent”).innerHTML+=content; } //页面控件 var totalPages=Math.ceil(response.searchInformation.totalResults/10); var currentPage=数学楼层(开始/10+1); var pageControls=“”; //页面更改控件,最多10个。
对于(var x=1;x如果响应不包含项,则处理程序将一次又一次地将您重定向到同一页面。API返回的任何错误都可能发生这种情况(例如错误的API凭据、超出配额等)。在这种情况下,以下代码将
start
设置为负值(甚至设置为
function hndlr(response) {
        if (response.items) {
            if (response.items == null) {
                //Sometimes the results say there are 34 results/4 pages, but when you click through to 3 then there is only 30, so page 4 is invalid now.
                //So if we get to the invalid one, send them back a page.
                window.location.replace("results.html?start=" + (start - 10) + "&q=" + query);
                return;
            }
            //Search results load time
            document.getElementById("resInfo-0").innerHTML = "About " + response.searchInformation.formattedTotalResults + " results (" + response.searchInformation.formattedSearchTime + " seconds)";
            //Clear the div first, CMS is inserting a space for some reason.
            document.getElementById("googleContent").innerHTML = "";
            //Loop through each item in search results
            for (var i = 0; i < response.items.length; i++) {
                var item = response.items[i];
                var content = "";

                content += "<div class='gs-webResult gs-result'>" +
                    "<table class='gsc-table-result'><tbody><tr>";
                //Thumbnail image
                // if (item.pagemap.cse_thumbnail != null)
                //     content += "<td class='gsc-table-cell-thumbnail gsc-thumbnail'><div class='gs-image-box gs-web-image-box gs-web-image-box-portrait'><a class='gs-image' href='" + item.link + "'>" +
                // "<img class='gs-image' class = 'gs-image-box gs-web-image-box gs-web-image-box-portrait' src='" + item.pagemap.cse_thumbnail[0].src + "'></a></td>";
                //Link
                content += "<td><a class='gs-title' href='" + item.link + "'>" + item.htmlTitle + "</a><br/>";
                //File format for PDF, etc.
                if (item.fileFormat != null)
                    content += "<div class='gs-fileFormat'><span class='gs-fileFormat'>File Format: </span><span class='gs-fileFormatType'>" + item.fileFormat + "</span></div>";
                //description text and URL text.
                content += item.htmlSnippet.replace('<br>', '') + "<br/><div class='gs-bidi-start-align gs-visibleUrl gs-visibleUrl-long' dir='ltr' style='word-break:break-all;'>" + item.htmlFormattedUrl + "</div>" +
                    "<br/></td></tr></tbody></table></div>";
                document.getElementById("googleContent").innerHTML += content;
            }
            //Page Controls
            var totalPages = Math.ceil(response.searchInformation.totalResults / 10);
            var currentPage = Math.floor(start / 10 + 1);
            var pageControls = "<div class='gsc-results'><div class='gsc-cursor-box gs-bidi-start-align' dir='ltr'><div class='gsc-cursor'>";
            //Page change controls, 10 max.
            for (var x = 1; x <= totalPages && x <= 10; x++) {
                pageControls += "<span class='gsc-cursor-page";
                if (x === currentPage)
                    pageControls += "gsc-cursor-current-page";
                var pageLinkStart = x * 10 - 9;
                pageControls += "'><a href='results.html?start=" + pageLinkStart + "&q=" + query + "'>" + x + "</a>&nbsp;&nbsp;</span>";
            }
            pageControls += "</div></div></div>";
            document.getElementById("googleContent").innerHTML += pageControls;
        }
        else {
            document.getElementById("googleContent").innerHTML = "No result found on " + query + ", try other";
        }
    }