Reputation: 23
I want to load json information from another page in my site with ajax. here is what i have so far
$(function() {
$('#show-more').bind('click', function() {
$.ajax({
url: 'http://localhost:3000/users/10',
dataType: 'json',
success: function(data) {
alert(data);
}
});
});
})
When I do this, the alert popups up and I get [OBJECT OBJECT] [OBJECT OBJECT]
. How can I take this data and append it to my feed id on the page. I tried this in place of alert(data)
:
$('#feed').append(data);
However I get this error "fragment.appendChild( ret[i] ); " in my console. How can I do what I want properly?
Also, there is a field in the data i am retrieving titled message that I am trying to access. How could I access it? Would i do something like data.message?
Thanks in advance!
Upvotes: 2
Views: 342
Reputation: 24969
The fact that the alert shows that you have an object is great. JSON is JavaScript Object Notation and as such, you should expect to receive an object as data in the success method.
Depending on the type, you can access the data in different ways. You won't be able to "append" it directly to another element as it's not HTML. So if the JSON is a single object, you can do this:
alert(data.id)
Where "id" is the name of one of the properties of the object. Or if the data is an array of objects, you can do this:
$.each(data, function()
{
alert(this.id);
});
Regardless of the type, you'll have to manually create the HTML.
Upvotes: 3
Reputation: 134
Use this to give you a quick idea of what's going on:
<?php
echo json_encode(array('test' => 'This is a test'));
?>
Then in your jquery change alert(data), to alert(data.test). That should get you started - or at least work as a sample to build on. Good luck!
Upvotes: 0
Reputation: 6544
Data is javascript object. There's probably properties on it that have the data you're looking for. If data.message = "foo"
, then doing alert(data.message)
will output "foo";
If you want to see the properties on data you can do one of a couple things:
1) Put a breakpoint on the line containing alert(data);
In chrome's Javascript console, or Firefox's Firebug extension you can put a breakpoint on a line and see the the values of all the variables.
2) You can loop through it:
var str = "";
for(var prop in data){
str += prop + ": " + data[prop] + "\n";
}
alert(str);
This will show you all the properties on data. Some of those properties may also be objects, in which case you'll have to iterate through those as well.
Upvotes: 1