This is getting pretty frustrating and i thought this would be alot easier to do, all i'm trying to do is use a rails app i've created as an API, i couldn't seem to get it to work so i created a quick little test app to eliminate any thing that could really be complicated about it, I know very basic java script and my experience doesn't go much further then using Jquery for various effects ect.
I am using the rails-api gem, all I've done in this test is simply ran
Rails g scaffold user name
No views or anything like that has been created, when you navigate to the users path you will see a json array containing the users (currently the only fields would be created, updated, name and id)
Here's my code.
$(document).ready(function(){
$('#new_user').submit(function(e) {
$.post('/users', $(this).serialize());
this.reset();
e.preventDefault();
});
$.getJSON('/users', function(users) {
$.each(users, function(user) {
var output = "<li>" + user.name + "</li>";
$('#content ul').append(output);
});
});
});
What the json that .getJson points to looks like
[{"user":{"created_at":"2013-01-23T02:30:42Z","id":1,"name":"test","updated_at":"2013-01-23T02:30:42Z"}},
{"user":{"created_at":"2013-01-23T02:31:49Z","id":2,"name":"test","updated_at":"2013-01-23T02:31:49Z"}}]
Posting works fine, but when when ran, the fields print Undefined, previously if i put user.user.name it would work just fine, obviously that doesn't seem like the best route though.
Is there something I'm missing or is this more complicated then i originally though, I figured all that would really be required to create an API client for my app would be to parse the json like i have here and simply output it to divs.
You need to use user.user.name
. $.each
iterates over the array, but each has an object with the user
key and the name
key is inside that.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.