使用Google Suggest和JavaScript

Toa*_*ast 2 html javascript autocomplete

我想将Google搜索的自动填充/推荐功能添加到HTML页面中的输入中.

如果我用Firefox 打开这样的URL:

suggestqueries.google.com/complete/search?client=firefox&q=stacko&callback=abc
Run Code Online (Sandbox Code Playgroud)

它下载这样的文件:

["stacko",["stackoverflow","stackoverflowerror","stackoverflowexception","stackops","stackoverflow api","stackoverflow careers","stackoverflow java","stackoverflow deutsch","stackoverflow wiki","stackoverflow reputation"]]
Run Code Online (Sandbox Code Playgroud)

我怎样才能在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);
Run Code Online (Sandbox Code Playgroud)

这会创建一个空警报.

dan*_*vis 6

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 );
}
Run Code Online (Sandbox Code Playgroud)

//示例用法(谷歌):

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"
]
Run Code Online (Sandbox Code Playgroud)

//示例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"
]
Run Code Online (Sandbox Code Playgroud)