2011-06-15 127 views
1

這來自Parse JSON Freebase results in PHP 但是,因爲它有可能在Javascript中使用JSONP,我會想知道如何。JSONP Freebase的自動完成jquery插件

所以,我用這個jQuery自動完成插件:http://devthought.com/wp-content/projects/jquery/textboxlist/Demo/

這是使用的輸入插件代碼:

$(function() { 
    var t = new $.TextboxList('#form_topick_tags', {unique: true, plugins: {autocomplete: { 
      minLength: 2, 
      queryRemote: true, 
      remote: {url: 'autocomplete2.php'} 
     }}}); 

我想解析來自遊離鹼,如結果http://www.freebase.com/private/suggest?prefix=beatles&type_strict=any&category=object&all_types=false&start=0&limit=10&callback=

,並把它傳遞給插件順序:

guid,"name",null,"name<span>n:type name</span>" 

所以,第一個結果將是:

0,"The Beatles",null,"The Beatles<span>Band</span>" 
+0

這是一個很好的計劃!所以..你在問什麼? – Arend 2011-06-15 08:38:04

回答

2
<input id="form_topick_tags" /> 

<!-- Adjust the script tag locations per your set-up --> 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script> 
<script src="GrowingInput.js" type="text/javascript" charset="utf-8"></script>   
<script src="../Source/TextboxList.js" type="text/javascript" charset="utf-8"></script>  
<script src="../Source/TextboxList.Autocomplete.js" type="text/javascript" charset="utf-8"></script> 
<!-- required for TextboxList.Autocomplete if method set to 'binary' --> 
<script src="../Source/TextboxList.Autocomplete.Binary.js" type="text/javascript" charset="utf-8"></script>  


<script type="text/javascript"> 
var search = 'beatles', 
    myJSONArray = []; 

$(function() { 
    var t = new $.TextboxList('#form_topick_tags', { 
     unique: true, 
     plugins: { 
      autocomplete: { 
       minLength: 2 
      } 
     } 
    }); 

    $.ajax({ 
     dataType:'JSONP', 
     success: function (obj) { 
      for (var i=0, orl=obj.result.length; i < orl; i++) { 
       var o = obj.result[i]; 
       myJSONArray.push([o.guid, o.name, o.name+'<span>'+o['n:type'].name+'</span>']); 
      } 

      // For testing: 

      // alert(myJSONArray); 
      // You can just use myJSONArray, but if you need JSON, see http://json.org for a JSON converter; in modern browsers, JSON is supported by default 
      //alert(JSON.stringify(myJSONArray)); 

      t.plugins['autocomplete'].setValues(myJSONArray); 
     }, 
     url: 
     'http://www.freebase.com/private/suggest?type_strict=any&category=object&all_types=false&start=0&limit=10&prefix='+encodeURIComponent(search) 
    }); 
}); 
</script> 
+0

我是否必須將'搜索'var聲明爲'beatles'?因爲「搜索」必須是輸入字段上的文本... – Santiago 2011-06-15 17:30:27

+0

不,你不知道。只需替換要搜索的輸入字段的值,例如'var search = document.getElementById('mysearchElement')value,'並根據按鈕單擊事件運行整個代碼,而不是在頁面上運行。 – 2011-06-15 18:36:42