JNM
JNM

Reputation: 1195

jquery parse json array fails

I have json array like this one:

[{"code" : "A1", "desc" : "desc1"},{"code" : "A2", "desc" : "desc2"}]

How should i parse it in jquery to get data like this:

A1 - desc1
A2 - desc2

I tried lots of different ways, but none of them works. At the moment i have a code like this:

$.ajax({
    url: 'my_url',
    success: function(data) {
        $.each(data, function (key, val) {
            alert(val.code);
        });
    },
    error: function() {
        alert('problem');
    }
});

Upvotes: 0

Views: 1305

Answers (3)

JNM
JNM

Reputation: 1195

Ok, i solved my problem. The problem was my hosting provider. I am using Codeigniter as a framework, and return result as json. My hosting provides adds 3 additional lines to the result (uses them for tracking opened pages). Problem was, that i was checking json, which i see in browser, but when i rightclicked and checked source code, i found those lines.

Upvotes: 0

Sushanth --
Sushanth --

Reputation: 55740

You can also try setting the

dataType:'json' // to your ajax request

After adding this try to check with parseJson and sans parseJson

Upvotes: 2

bhb
bhb

Reputation: 2561

Use

jQuery.parseJSON( json )

Change code to

$.ajax({
   url: 'my_url',
   success: function(data) {
      var jsonData = jQuery.parseJSON(data);
      $.each(jsonData, function (key, val) {
        alert(val.code);
      });
  },
  error: function() {
    alert('problem');
  }
});

EDIT: Working fiddle

Cheers!!

Upvotes: 0

Related Questions