2011-12-15 43 views
3

Google建議以XML表的形式在線提供,例如,這些建議是關於字堆棧的建議:XML results by Google。這裏是一個截斷版本:Google XML建議

<toplevel> 
    <CompleteSuggestion> 
    <suggestion data="stack overflow"/> 
    <num_queries int="25200000"/> 
    </CompleteSuggestion> 
    <CompleteSuggestion> 
    <suggestion data="stackable washer dryer"/> 
    <num_queries int="1050000"/> 
    </CompleteSuggestion> 
    <CompleteSuggestion> 
    <suggestion data="stacked"/> 
    <num_queries int="57000000"/> 
    </CompleteSuggestion> 
    … 
</toplevel> 

我想在我的網站上放置一個輸入字段,並在輸入時得到建議。我如何獲得XML並在我的網站上顯示它像普通的HTML(文本)?

(我能做到這一點與jQuery?)

+0

是的,你可以使用jQuery。尋找自動完成插件。 – 2011-12-15 10:18:07

回答

5

檢索XML數據跨域你可以使用YQL檢索數據並將其轉化爲JSONP。

爲了顯示建議,你可以使用jQuery UI的Autocomplete

$("#term").autocomplete({ 
    minLength: 2, 
    source: function(request, response) { 
    $.ajax({ 
     url: 'http://query.yahooapis.com/v1/public/yql', 
     dataType: 'JSONP', 
     data: { 
     format: 'json', 
     q: 'select * from xml where url="http://google.com/complete/search?output=toolbar&q=' + encodeURIComponent(request.term) + '"' 
     }, 
     success: function(data) { 
     response($.map(data.query.results.toplevel.CompleteSuggestion, function(item) { 
      return { label: item.suggestion.data, value: item.suggestion.data }; 
     })); 
     } 
    }); 
    } 
}); 

HERE是代碼。

+0

非常感謝:)這將花費我的時間.. – Youss 2011-12-15 14:01:34