开发者

jQuery Autocomplete won't display JSON response from PHP

I'm stuck with the implementation of the jQuery Autocomplete. I'm using this tutorial: http://1300grams.com/2009/08/17/jquery-autocomplete-with-json-jsonp-support-and-overriding-the-default-search-parameter-q/

My jQuery code is this:

$("#quickSearchQuery").autocomplete("http://mydomain.net/json.php", {
    dataType: 'json',
    selectFirst: true,
    minChars: 2,
    max: 8,
    parse: function(data) {
        var rows = new Array();
        data = data.members;
        for(var i = 0; i < data.length; i++) {
            rows[i] = { id : data[i].id, name : data[i].name, location : data[i].location };
        }
        return rows;
    },
    formatItem: function(row, i, n) {
        return row.name + ' (' + row.location + ')';
    }
});

A call to http://mydomain.net/json.php?q=Alb produces a JSON response like this:

{"query":"Alb","members":[{"id":"1","name":"Peter Albert","location":"New York"},{"id":"4","name":"Adalbert S开发者_如何转开发mith","location":"Alabama"},{"id":"42","name":"Albert Einstein","location":"Vienna"}]}

My problem is: It just doesn't work. The Autocomplete doesn't appear, no elements are created. If I run the code from the tutorial, everything is fine and I get the autocompleted list of cities. But even if I only change the source URI and from data.geonames to data.members (and so on), the autocompleter stops working.

What I've tried:

  • I changed dataType to jsonp and json, but jsonp creates the 'invalid label' error on the JSON file
  • I modified the PHP script's content-type with header("Content-Type: application/json");
  • I tried all the other Autocompleters, but nothing changed
  • I tried all the fixes I have found from responses at Stack Overflow and tutorials in the web
  • I copied a JSON response from geonames.org into a file, uploaded it to my server and used this hardcoded response as lookup source. Still no autocompleter showing :(

Maybe you got an idea?

Thanks! Joe


with autocomplete, you must use the property id and value to make it working. Only those properties are used to render the list.

In your php object, declare something like this (this one comes from C#, but think that you understand it):

public class Product
    {
        public String id { get; set; } //must be used
        public String value { get; set; } //must be used
        public String marque { get; set; }
    }

and return the json-serialized string to the client.

The json is something like that

[{"id":"1","value":"UMTS","comment":"umts comment"},
{"id":"2","value":"RAN","comment":"ran comment"},
{"id":"3","value":"Swap","comment":"swap comment"}]

It will be auto-mapped in your JS and the autocomplete should work for now.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜