Jquery problem with json data in complex structure

22 Views Asked by At

My Jquery Autocomplete using the sample code from JQuery website work with below data from a url

 [
    "shirt",
    "shirt two"
]

But wont work with below data [ data from a url ]

[
{
    "id": 1,
    "name": "shirt"
},
{
    "id": 5,
    "name": "shirt two"
}

]

and Here is my JQuery :

<script>
$(function(){
    $('#searchbox').autocomplete({
        type: "GET",
        source:'{% url 'ajitemsdetails' %}',
        minLength: 3,
        select: function( event, ui ) {                 
            $('#data').append('<tr><td></td><td>'+ui.item.name+'</td><td></td><td></td><td></td><tr>');
    }})
});
</script>
1

There are 1 best solutions below

0
Bineesh Kumar On

The problem was in the json output. After hours of try and error and sweat :) i could fix this by changing the server code to create the json as :

itemlist = []
         
    for item in items:
        itemdic = {}  
        itemdic['label'] = item.id
        itemdic['value'] = item.name
        itemlist.append(itemdic)            
    return JsonResponse(itemlist, safe= False)

and this gave the below output at the server to the call :

[{"label": 1, "value": "shirt"}, {"label": 5, "value": "shirt two"}]