首先我在google doc中找到了这个演示:
<html>
<head>
<title>JSON/Atom Custom Search API Example</title>
</head>
<body>
<div id="content"></div>
<script>
function hndlr(response) {
// handle result
}
</script>
<script src="https://www.googleapis.com/customsearch/v1?key=KEY&cx=cx&q=cars&callback=hndlr">
</script>
</body>
</html>
它运作正常。
但是我知道我想在js文件中触发“搜索过程”,说mySearch.js,那么我怎么能完成这个呢?
示例:
var XXXLayer = cc.Layer.extend({
init:function () {
this._super();
var theUrl = 'https://www.googleapis.com/customsearch/v1?key=KEY&cx=cx&q=cars&callback=hndlr';
// what to do here ???????
return true;
},
hndlr:function(response) {
// handle result
}
});
感谢任何建议,谢谢:)
答案 0 :(得分:1)
您可以在触发搜索过程时添加脚本元素。
function triggersearch(){
var query=document.getElementById("query").value;
var JSElement = document.createElement('script');
JSElement.src = 'https://www.googleapis.com/customsearch/v1?key=KEY&cx=KEY&q='+query+'&callback=hndlr';
document.getElementsByTagName('head')[0].appendChild(JSElement);
}
答案 1 :(得分:0)
使用@RamK中的代码,执行以下操作:
index.html:
<html>
<head>
<title>Example</title>
</head>
<body>
<div id="query"></div>
<script src="cs.js"></script>
</body>
</html>
cs.js:
var key = "your api key"; // API KEY
var id = "your custom search engine id"; // CSE ID
var q = "cats"; // QUERY
function hndlr(response) {
console.log(response); // a way to see your results
}
function triggersearch(){
var query=document.getElementById("query").value;
var JSElement = document.createElement('script');
JSElement.src = `https://www.googleapis.com/customsearch/v1?key=${key}&cx=${id}&q=${q}`+query+'&callback=hndlr';
document.getElementsByTagName('head')[0].appendChild(JSElement);
}
triggersearch();