问题
Is it possible to pass a search variable into the Google Custom Search Engine that I have embedded on my website? I can get the search engine to work, but I can't pass it a term via POST (it's coming from a search button on other pages of the website)
I tried to hack the code I found here: http://code.google.com/apis/ajax/playground/?exp=search#hello_world
And this is what I have so far... ($q is the term I am passing to it)
<script type="text/javascript">
google.load('search', '1', {language : 'en'});
function OnLoad()
{
var customSearchControl = new google.search.CustomSearchControl('***my key****');
customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
customSearchControl.draw('cse');
searchControl.execute("$q");
}
google.setOnLoadCallback(OnLoad);
</script>
Thanks
回答1:
Sorry, I know it's a crappy answer, but you've actually got it right apart from referencing the wrong variable name. Oh, also, as an aside, I would also hope you're doing some kind of sanitisation on $q, in case someone posted something like this to your form: term"); alert("aha!
customSearchControl.draw('cse');
searchControl.execute("$q");
should be:
customSearchControl.draw('cse');
customSearchControl.execute("$q");
Also, thank you for the question - I was looking for how to do this myself!
回答2:
This is to help anyone using PHP trying to accomplish this same goal. The example above uses...
customSearchControl.execute("$q");
to read the parameter being passes in. On a PHP site you would use...
customSearchControl.execute("<?php echo $_POST['your_paramter_name_here'];?>");
You could use $_GET or $_REQUEST if your parameter is not in the post.
Of course you should should sanitize the input first. Something like this is pretty weak but it's a start...
customSearchControl.execute("<?php echo htmlentities( trim( $_POST['your_paramter_name_here'] ), ENT_QUOTES );?>");
回答3:
In case someone is looking for a bit more straight forward / simple solution. All you have to do is to pass search keywords into GET parameter named q (from your custom form into page where your GCS is), GCS will automatically use that search phrase.
Source: https://developers.google.com/custom-search/json-api/v1/using_rest
来源:https://stackoverflow.com/questions/2298027/pass-variable-to-google-custom-search-engine