开发者

Help getting correct info passed to the Jquery Autocomplete plugin for a clickable result

So I have a problem with the following code. I have an array that is formatted:

{label:movie, value:location} 

The following code will only show the label in the search box and when clicked uses that information to make the url. I need it to pass the value field from the array instead of the label. I've tried changin开发者_Python百科g suggestions.push(val.label) to suggestions.push(val.value) at which point the clicking url works but the url shows in the searchbox instead of the label. I'm new to Jquery and Json so am really flying blind.

$(function(){
    //attach autocomplete
    $("#to").autocomplete({
        minLength: 2,

        //define callback to format results
        source: function(req, add){

        //pass request to server
        $.getJSON("/movie.php?callback=?", req, function(data) {

                //create array for response objects
                var suggestions = [];

                //process response
                $.each(data, function(i, val){                                
                    suggestions.push(val.label);
                });

                //pass array to callback
                add(suggestions);
            });

        },
        focus: function (event, ui) {
            $(event.target).val(ui.item.label);
            return false;
        },
        select: function (event, ui) {
            $(event.target).val(ui.item.label);
            window.location = ui.item.value;
            return false;
        },
    });
});


You are close. You don't need the post-processing that you're doing in the success callback:

source: function(req, add){
    //pass request to server
    $.getJSON("/movie.php?callback=?", req, add);
},

The autocomplete widget can take an array of objects, as long as those objects have a label and/or value property.

Since you've supplied both in the result of your AJAX call, you should get the behavior you want by calling the add function directly as the success method of your AJAX callback.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜