【发布时间】:2010-12-01 17:54:56
【问题描述】:
我做了一个 jquery .ajax 调用,我期待一个 json 结果。 问题是,如果有 5 个作者,我会得到 author_details_0、author_details_1、author_details_2 等。如何动态构造要从 json 检索的变量名称?我不知道我会得到多少作者,可能有数百个。
$.ajax({
type: "POST",
url: "/authordetails/show_my_details/",
data: af_pTempString,
dataType: "json",
beforeSend: function() {
},
success: function(jsonData) {
console.log("Incoming from backend : " + jsonData.toSource());
if(jsonData.AuthorCount)
{
console.log("Number of Authors : " + jsonData.AuthorCount);
for (i = 0; i < jsonData.AuthorCount; i++)
{
temp = 'author_details_' + i; <-------------------This is the name of the variable I'm expecting.
console.log("Farm information : " + eval(jsonData.temp) ); <----- This doesn't work, how can I get jsonData.author_details_2 for example, 'coz I don't know how many authors are there, there could be hundreds.
}
}
如果您知道如何解决此问题,请告诉我! 非常感谢。
【问题讨论】:
-
为什么需要 author_details_0、1、2 等?
-
你是如何生成 json 的?
-
我在后端使用 dJango。我创建的数据模型有 Author 和相关的 Author_Details 表。给定一个发布者 ID,我查询并获取我简单序列化的作者集 - json_serializer.serialize(allAuthors, ensure_ascii=False)。这不会序列化作者详细信息,因此我必须遍历作者对象数组并手动创建它们,因此 author_details_XX 其中 XX 是作者主键。我不确定是否有办法将作者和其他详细信息捆绑为单个 JSON 数组对象。如果有的话,我很乐意改造我的代码,因为它更干净。
标签: jquery json dynamic variables