sun-the
sun-the

Reputation: 17

how to parse dict in javascript

$.post("http://10.0.1.101:9000/search/", {q: ""+inputString+""}, function(data){
    if(data.length >0) {
     alert(data);
     $('#suggestions').show();
     $('#autoSuggestionsList').html(data);

    }
   });

alert(data) gives me : 
    {"result": ["taxo",  "tere", "tuy"], "success": "True"}

But I want that the alert gives me ["taxo", "tere", "tuy"]only this value. alert(data['result']) gives me undefined value.

Upvotes: 0

Views: 561

Answers (3)

Martin Jespersen
Martin Jespersen

Reputation: 26183

You need to change your code to look like this:

$.post("http://10.0.1.101:9000/search/", {q: ""+inputString+""}, function(data){
  if(data.length > 0) {
    alert(data);
    $('#suggestions').show();
    $('#autoSuggestionsList').html(data);
  }
 },'json');

Notice the 'json' part of the $.post call - it tells jQuery to expect json in the result, and parse it into a javascript object that can be accessed like you wish.

Look here for the full documentation

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038780

data.result will give you the list, so you could:

alert(data.result.join(','));

Also make sure that you have specified a proper content type on your server: application/json or jquery won't parse the result to a JSON object. If you don't have control over the server you could specify the dataType parameter on the client:

$.ajax({
    url: 'http://10.0.1.101:9000/search/',
    data: { q: inputString }, 
    dataType: 'json',
    success: function(data) {
        if(data.result > 0) {
            $('#suggestions').show();
            $('#autoSuggestionsList').html(data.result.join(','));
        }
    }
});

Upvotes: 0

Pim
Pim

Reputation: 131

I think your data is returned as a string. When using $.post({}), you need to tell jQuery that you expect data in JSON format:

$.ajax({dataType: json, type: post, ...});

See: http://api.jquery.com/jQuery.ajax/

Upvotes: 0

Related Questions