Errors with Google Custom Search popular queries

雨燕双飞 提交于 2019-12-11 09:44:10

问题


I've got a custom search on a website and I'd like to display the most popular searches using the Custom Search Popular Queries option. First off, the code Google gives in the process is wrong - I kept getting bad requests. This SO post helped me rebuild the correct URL, but now I'm getting a syntax error.

When I run the test, I get, Uncaught SyntaxError: Unexpected token : in the console from the JSON information that comes back.

Here's my HTML:

<div id="queries"></div>
        <script src="https://cse.google.com/query_renderer.js"></script>
        <script src="https://www.google.com/cse/api/USERID/cse/CSEID/queries/js?view=overall&callback=(new+PopularQueryRenderer(document.getElementById('queries'))).render"></script>

The colon throwing the error is after title, but I can't figure out why that would be happening.

{
"title" : "MTBoS Search Engine",
"popularQueries" : [ ...rest of the results array... ]
}

Lastly, I tried calling the JSON response from a formatting checker by copying and pasting the call URL and it returned with a handful of HTML errors. Could it be an issue with the query renderer script?

Any help is appreciated.


回答1:


If you look at the example on Google (you should be able to see it at the bottom of your Google Custom Search/Statistics and Logs page), you should see that instead of single quotes, Google’s example uses encoded double-quotes:

<script src="https://www.google.com/cse/api/USERID/cse/CSEID/queries/js?view=overall&callback=(new+PopularQueryRenderer(document.getElementById(%22queries%22))).render"></script>

I do not understand why single quotes do not work there, however, I have verified that for me at least they do not. If I put single quotes there, I get the error you saw:

SyntaxError: Unexpected token ':'. Parse error.

If I put percent-encoded quotes there, it successfully creates the list of popular queries.

It appears to be the single quotes that are the issue, not that they aren’t encoded for use in URLs. If I replace %22 with %27 (encoded single quotes), the same “Unexpected token” error results.

If there is a reason you wish to avoid the percent-encoding, it is legal to use single quotes to surround attributes, so you could do this:

<script src='https://www.google.com/cse/api/USERID/cse/CSEID/queries/js?view=overall&callback=(new+PopularQueryRenderer(document.getElementById("queries"))).render'></script>

According to the HTML specs, double quotes are legal inside of single quotes, and I’ve verified that this also works on my search page.



来源:https://stackoverflow.com/questions/31272299/errors-with-google-custom-search-popular-queries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!