1

I am sending a JSON encoded array from my controller to my view page. I am doing this on my view page to get the data:

 function () {
     $.get('http://localhost/Location/loc', function(data){
         alert(data[0].message);
     });
 }

The data is like this

 {"message":"hello!"}

I am alerting the value of message but my alert giving me undefined. My question is how can I access values of JSON array?

I am new to JSON so I don't know much about JSON.

rink.attendant.6
  • 44,500
  • 61
  • 101
  • 156
mynameisbutt
  • 167
  • 1
  • 3
  • 22

3 Answers3

1

You data contains a single object, not an array.

In your case use alert(data.message); instead.

An array is defined using [] brackets, for example [{message:"hello"}, {message:"world"}] is an array with two objects in it.

Knaģis
  • 20,827
  • 7
  • 66
  • 80
  • @mynameisbutt - did you use Fiddler or another tool to see what exactly is returned from the server? – Knaģis Sep 22 '13 at 10:53
1

Try changing your function to:

function () {
     $.get('http://localhost/Location/loc', function(data){
         alert(data.message);
     }, 'json');
}

This is because jQuery probably doesn't know that the response data is JSON, so it's assuming that it's plaintext. You can explicitly specify it in $.get as the last parameter as in the revised code, or configure your server to send the response with the HTTP Content-Type header of application/json.

I'm assuming this because message is not a property of a String and that's why you're getting undefined.

Alternatively, you may use $.getJSON:

function () {
     $.getJSON('http://localhost/Location/loc', function(data){
         alert(data.message);
     });
}

Also note that I have changed the alert to data.message. See Knaģis' answer for explanation.

rink.attendant.6
  • 44,500
  • 61
  • 101
  • 156
0

OK, if this does not work:

function () {
     $.get('http://localhost/Location/loc', function(data){
         alert(data.message);
     });
}

try this:

function () {
     $.get('http://localhost/Location/loc', function(data){
         alert(data.message);
     }, 'json');
}
srain
  • 8,944
  • 6
  • 30
  • 42