2013-05-06 66 views
2

我想將Google搜索的自動完成/建議功能添加到HTML頁面的輸入中。使用Google建議使用JavaScript

如果我打開一個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); 

創建一個空的警報。

+2

您可以在輸入元素上使用'onkeyup'和'onkeydown'等事件,驗證輸入,然後對'suggestqueries.google.com ...'URL進行ajax調用,解析響應並操作DOM以顯示建議。任何時候你被困住了,**在這裏發佈你的代碼**和問題描述,你的問題將在幾分鐘內解決:) – Ejaz 2013-05-06 20:59:41

+1

可能想查看[jQuery UI的自動完成](http:// jqueryui的.com /自動完成/)。 – Dom 2013-05-06 21:00:37

+0

@Ejay我的問題只是爲了得到Google的建議。問題不在於UI。用這些建議來顯示警報就可以了。 – Toast 2013-05-06 21:05:16

回答

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" 
] 
+0

這適用於我。是否有可能使用其他建議來源? – Toast 2013-05-06 21:39:51

+0

是的,我已經用另一個使用wikipedia而不是谷歌的例子更新了答案。 – dandavis 2013-05-06 21:50:05

+0

在yql查詢中需要'encodeURIComponent(encodeURIComponent(term))'來處理需要在搜索詞中進行編碼的任何內容(如空格)。 – Dave 2016-04-09 20:19:39

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請求到那個頁面。

+0

'xhr.send();'產生'NS_ERROR_DOM_BAD_URI:訪問受限的URI被拒絕的錯誤。 – Toast 2013-05-06 21:20:33

3

你可以使用這樣的事情,它採用了谷歌搜索網址,結合YQLjQuery UI autocomplete

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

我沒有寫所有在這裏的香草jQuery的東西JavaScript,因此你可以使用它作爲一個概念證明的時間。但說實話,這是我實際上使用jQuery和jQuery UI而不是重新發明輪子的時代之一。當然還有其他第三方庫可以爲你做類似的事情。而且,如上所述,您可以通過更改YQL搜索網址來爲自動填充使用不同的來源。