gpt4 book ai didi

javascript - 将 Google Suggest 与 JavaScript 结合使用

转载 作者:太空宇宙 更新时间:2023-11-04 13:47:48 25 4
gpt4 key购买 nike

我想将 Google 搜索的自动完成/建议功能添加到 HTML 页面中的输入。

如果我打开 URL像这样使用 Firefox:

suggestqueries.google.com/complete/search?client=firefox&q=stacko&callback=abc

它下载这样的文件:

["stacko",["stackoverflow","stackoverflowerror","stackoverflowexception","stackops","stackoverflow api","stackoverflow careers","stackoverflow java","stackoverflow deutsch","stackoverflow wiki","stackoverflow reputation"]]

我如何在 JavaScript 中执行此操作?我想得到一个包含结果的数组。

//编辑:这是我试过的代码:

var txtFile = new XMLHttpRequest();
txtFile.open("GET", "http://suggestqueries.google.com/complete/search?client=firefox&q=stacko&callback=abc", true);
txtFile.onreadystatechange = function() {
text = txtFile.responseText;
alert(text);
}
txtFile.send(null);

这会创建一个空警报。

最佳答案

function addScript(u){ 
var s=document.createElement('script');
s.src=u;
document.getElementsByTagName('*')[1].appendChild(s);
}


function getQueryWiki(term, callback){
var id="i"+Math.random().toString(36).slice(2);
getQueryWiki[id]=function(data){ callback(data); delete getQueryWiki[id];};
addScript( "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D%22http%3A%2F%2Fen.wikipedia.org%2Fw%2Fapi.php%3Faction%3Dopensearch%26search%3D"+
encodeURIComponent(term)+
"%26namespace%3D0%22%20&format=json&callback=getQueryWiki."+id );
}


function getQueryGoogle(term, callback){
var id="i"+Math.random().toString(36).slice(2);
getQueryGoogle[id]=function(data){ callback(data); delete getQueryGoogle[id];};
addScript( "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D%22http%3A%2F%2Fsuggestqueries.google.com%2Fcomplete%2Fsearch%3Fclient%3Dfirefox%26q%3D"+
encodeURIComponent(term)+
"%22%20&format=json&callback=getQueryGoogle."+id );
}

//示例用法(谷歌):

getQueryGoogle("obam", function(d){
alert(
JSON.stringify(
d.query.results.json.json[1].json,
null,
"\t"
)
);
});

// displays:

[
"obama",
"obamacare",
"obama immigration",
"obama phone",
"obama gun control",
"obama immigration reform",
"obama impeachment",
"obama approval rating",
"obama net worth",
"obama speech"
]

//示例 2(维基百科)

getQueryWiki("obam", function(d){
alert(
JSON.stringify(
d.query.results.json.json[1].json,
null,
"\t"
)
);
});

//shows:

[
"Obama",
"Obama administration",
"Obamacare",
"Obama-Biden Transition Project",
"Obama, Fukui",
"Obama stimulus plan",
"Obama Line",
"Obama for America",
"Obama Domain",
"Obama Republican"
]

关于javascript - 将 Google Suggest 与 JavaScript 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16407154/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com