2

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

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

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);

这会创建一个空警报。

4

3 回答 3

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 );
}

//示例用法(谷歌):

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"
]
于 2013-05-06T21:12:38.870 回答
4

你可以使用这样的东西,它结合了谷歌搜索 URL,结合了YQLjQuery UI 自动完成

HTML

<div class="ui-widget">
    <input id="search" />
</div>

Javascript

$(function () {
    $("#search").autocomplete({
        source: function (request, response) {
            $.ajax({
                url: "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(request.term) + "%22&format=json",
                dataType: "jsonp",
                success: function (data) {
                    response(data.query.results.json.json[1].json);
                }
            });
        },
        minLength: 2
    });
});

jsfiddle 上

我没有时间在这里用 vanilla javascript 编写所有 jquery 内容,因此您可以将其用作概念证明。但老实说,这是我实际使用 jquery 和 jquery UI 而不是重新发明轮子的时候之一。当然还有其他 3rd 方库可以为您做类似的事情。而且,如上所述,您可以通过更改 YQL 搜索 URL 为自动完成使用不同的来源。

于 2013-05-07T00:11:12.167 回答
1

不知道你到底想要什么,但就像@Ejay 在他的评论中说的那样,你可以这样做:

var xhr = new XMLHttpRequest();

xhr.onreadystatechange = function(){
    if(xhr.readyState == 4){
        if(xhr.status == 200){
           //parse the response object
           parse_the_text(xhr.responseText);    
        }
    }else{
      return;
    }
}

var url = "http://suggestqueries.google.com/complete/search?client=firefox&q=stacko";

xhr.open('Get', url, true);
xhr.send(null);

function parse_the_text(google_array){
    for(var i = 0; i < google_array[1].length; i++){  //this is dirty as it relies on response object never changing
        alert(google_array[1][i]);
    } 
}

但是我在jsfiddle上做了一些测试,它证实了 dandavis 所说的你不能向那个页面发送 ajax 请求。

于 2013-05-06T21:11:26.033 回答