这来自Parse JSON Freebase results in PHP 但是由于可以使用 JSONP 在Javascript中完成,我会想知道如何。
所以,我正在使用这个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'}
}}});
我想解析Freebase的结果,例如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 :(得分: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>