我正在使用 jquery 循环遍历 json 对象...但是有些似乎不起作用...
这是我的代码,
$.ajax({
type: "GET",
url: "/users/",
// data: "page="+pageNum,
async: false,
dataType: 'json',
success: function(data){
//alert("OK AJAX");
$("#search_btn").remove();
$('#btnadduser').css('visibility','visible');
$.each(data, function() {
$.each(this, function(k, v) {
/// iterate through the objects
$("#nbody").html("<tr style='background-color:#FFFFFF; font-size:14px;'> <td>"+data.f.user4.first_name+"</td> <td>"+data.f.user4.last_name+"</td><td>"+data.f.user4.username+"</td> <td>"+data.f.user4.email+"</td> <td>"+data.f.user4.username+"</td> <td>");
});
});
}
});
当我在终端中打印 json 对象时,这就是我得到的。
{"f":
{"user4": {"username": "user4", "first_name": "Alex", "last_name": "kasina", "is_active": true, "email": "alexkasina@gmail.com"},
"user5": {"username": "user5", "first_name": "", "last_name": "", "is_active": false, "email": "", }, "user2": {"username": "user2", "first_name": "", "last_name": "", "is_active": true, "email": ""},
"user3": {"username": "user3", "first_name": "", "last_name": "", "is_active": true, "email": ""},
"user1": {"username": "user1", "first_name": "", "last_name": "", "is_active": true, "email": ""},
"lexx": {"username": "lexx", "first_name": "", "last_name": "", "is_active": true, "email": "tas.ss@df.dc"}}}
我想遍历每个用户设置他们的名字,姓氏,用户名,......请帮忙?
风景
@login_required
def users(request):
from django.core.serializers.json import DjangoJSONEncoder
from django.forms.models import model_to_dict
html = User.objects.all()
f = {} # initialise the output
username = 'username' # one of the fields from myModel
[f.update({x[username]: x}) for x in [model_to_dict(y) for y in html]]
result = simplejson.dumps({"f" : f}, cls=DjangoJSONEncoder)
print result#To see the json object
return HttpResponse(result)