[英]Trouble with jquery.getJSON prints as undefined or states the function is undefined
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. 这变得越来越令人沮丧,我认为这样做会容易得多,我想要做的只是使用我作为API创建的Rails应用,我似乎无法使其正常工作,所以我创建了一个一个快速的小型测试应用程序,它消除了任何可能真正复杂的事情,我知道非常基本的Java脚本,并且我的经验与使用Jquery进行各种效果等相去甚远。
I am using the rails-api gem, all I've done in this test is simply ran 我正在使用rails-api gem,在此测试中所做的全部只是运行
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) 没有视图或类似的东西被创建,当您导航到用户路径时,您将看到一个包含用户的json数组(当前只有字段会被创建,更新,名称和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 .getJson指向的json看起来像什么
[{"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. 发布工作正常,但是当运行时,该字段打印未定义,以前如果我放user.user.name,它将正常工作,显然,这似乎不是最佳途径。
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. 有什么我想念的东西吗?还是比我原先要复杂的多,我想为我的应用程序创建API客户端真正需要的就是像我在这里解析json并将其简单地输出到div。
You need to use user.user.name
. 您需要使用
user.user.name
。 $.each
iterates over the array, but each has an object with the user
key and the name
key is inside that. $.each
遍历数组,但每个数组都有一个带有user
键的对象, name
键位于其中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.