2

I'm looking for a very very simple example where a Rails App does the following:

http://myapp.com/give_me_json

The returned data is a JSON:

[{"is_it_working":true, "very_simple_string":"Yes!"}]

I want to use the following function in JS to return the value of "is_it_working". But how???

function updateImpression(){

$.get('/give_me_json', function(data) {
    $('.da_place').html(data);
}

Instead this would return the whole json as a string.

1
  • Thank you guys for all the comment. I'm trying out each of the solutions to see which one I feel more confortable :) I read the jQuery website about the json method, but it was not clear about how to access the key value pairs. Commented Jan 20, 2012 at 19:50

4 Answers 4

1

Actually the response is array of json object so you need to get element from array 1st then property from json. SEE THE EXAMPLE

var response = [{"is_it_working":true, "very_simple_string":"Yes!"}];

//1 way
alert(response[0].is_it_working);

//2nd way
$(response).each(function(i,elem){
    alert(elem.is_it_working);
});
Sign up to request clarification or add additional context in comments.

1 Comment

True, but see the answer by @Diode for the real problem.
1

You can access it via data.is_it_working inside your $.get() method

2 Comments

-1 this is not correct, this wont work.. "data.is_it_working" is returning undefined. In this case the response is array of json. check my answer for more details.
Not if the mime type is wrong and the JS doesn't set the "json" dataType option for $.get.
1

If content type is text

$.get('/give_me_json', function(data) {
    var response = $.parseJSON(data); // or eval(data)
    $('.da_place').html(response[0].is_it_working);
});

If content type is JSON

$.get('/give_me_json', function(data) {
    $('.da_place').html(data[0].is_it_working);
}, "json");

Or

$.getJSON('/give_me_json', function(data) {
    $('.da_place').html(data[0].is_it_working);
});

1 Comment

This is the problem. Try console.log(data) to see that you got a string back and not a parsed object since you omitted the "json" argument.
0

would also need to specify 'json' in the get request so that jquery knows what do with what is returned

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.