开发者

How do I get JQuery Autocomplete to work with Ajax and JSON?

I am new to JQuery's autocomplete functionality. I am trying to get this code to work correctly. The code below correctly does an ajax poll every time someone types into the input field. However it does't drop down the autocomplete.

$(document).ready(function() {
  $("#search").autocomplete({
    source: 'cityajax'
  });
});

Here is the file it is successfully pulling from the server. The mime/content type is set to text/json.

['Overland Park','Hiawatha','Columbus','Lenexa','Pittsburg','Dodge City','Mission']

The same thing works fine when actual the source is set to an inline JSON var in the javascript itself. This problem has got to be something stupid simple, but I have spent the past hour and half trying to figu开发者_JAVA技巧re out what's wrong and I'm at a roadblock. Am I missing some kind of required parameter?

EDIT: Changed my "json" to this valid JSON, still same issue.

{"1": "Overland Park","1": "Hiawatha","1": "Columbus","1": "Lenexa","1": "Pittsburg","1": "Dodge City"}

EDIT: Changed my "json" again to this.

[{"1": "Overland Park"},{"2": "Hiawatha"},{"3": "Columbus"},{"4": "Lenexa"},{"5": "Pittsburg"},{"6": "Dodge City"}]

EDIT: Changed my "json" to this and everything was good.

[{"label": "Overland Park"},{"label": "Hiawatha"},{"label": "Columbus"},{"label": "Lenexa"},{"5": "Pittsburg"},{"label": "Dodge City"}]


The method you used is definitely not going to work. I'd question how you know the data is definitely getting there. Are you seeing it in XHR via Firebug? How are you calling it if you're not using the plugin's remote source functionality?

The way you've got it defined, there's no file extension. So, it's setting the source to a string called cityajax, which isn't valid. If your datasource is a variable called cityajax, then you could put that variable there without the quotes.

Jsonlint will allow you to test the validity of your data.


Simple example for the autocomplet:

$( "#test" ).autocomplete({
            source: "search.php"
                        })

In the search.php

<?php
    echo [{"label":"Overland Park"},{"label":"Hiawatha"}]
?>

If you want a local search, not Ajax than use the following code

var cityajax = ['Overland Park','Hiawatha','Columbus','Lenexa','Pittsburg','Dodge City','Mission']

$(document).ready(function() {
  $("#search").autocomplete({
    source: cityajax
  });
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜