-->

JSONP Freebase for autocomplete jquery plugin

2019-06-05 07:12发布

问题:

This comes from Parse JSON Freebase results in PHP But since its possible to do it in Javascript using JSONP, I would liek to know how.

So, I'm using this jquery Autocomplete plugin: http://devthought.com/wp-content/projects/jquery/textboxlist/Demo/

This is the code for using the plugin on an input:

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

I would like to parse the results from Freebase, e.g. http://www.freebase.com/private/suggest?prefix=beatles&type_strict=any&category=object&all_types=false&start=0&limit=10&callback=

and pass it to the plugin in this order:

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

So, the first result would be:

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

回答1:

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