【问题标题】:Jquery Json dynamic variable name generationJquery Json动态变量名生成
【发布时间】: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


【解决方案1】:

您可以通过两种方式访问​​对象属性。首先是点表示法,如在 object.property 中。您还可以使用括号表示法,如在 object['property'] 中。这里不需要评估:

 var propName = 'author_details_' + i;
 alert('Details for author ' + i + ' = ' + jsonData[propName];

This page 在底部解决您的假设。

【讨论】:

    【解决方案2】:

    解决了!

    而不是使用“temp” - 临时='author_details_'+我; 然后做 - 评估(jsonData.temp)

    这行得通 - eval("jsonData.author_details_" + i)

    由于数据来自数据库,所以是安全的,因为我在检查后将所有内容都放入了数据库中。因此 eval 不会构成安全威胁。

    如果您有更多解决方案,我会很高兴听到它们!

    【讨论】:

      【解决方案3】:

      为什么不将 json 存储为数组?而不是:

      {
          "author_details_1":
          {
              ...
          },
          "author_details_2":
          {
              ...
          },
          "author_details_3":
          {
              ...
          },
          "author_details_4":
          {
              ...
          }
          ...
      }
      

      试试

      {
          "author_details":
          [
              {
                  ...
              },
              {
                  ...
              },
              {
                  ...
              },
              {
                  ...
              }
          ]
          ...
      }
      

      然后你可以使用 author_details[i] 访问它。

      【讨论】:

        【解决方案4】:

        遇到了 jQuery 和 $.ajax 函数的问题。通过在 $.ajax 函数之外定义“数据”对象来解决:

        var data = new Object();
        data.ContentNodeID = button.siblings('.ContentNodeID').val();
        data.ContentObjectID = button.siblings('.ContentObjectID').val();
        data.ActionAddToBasket = '';
        data['eZOption['+$('[name=printFormatAttributeId]').val()+'][]'] = $('.eZOption').val();
        
        $.ajax({
            cache: false,
            type: 'POST',
            url: button.parent().attr('action'),
            data: data,
            success: function(data){
                         button.siblings('.addtobasket_success').css('display', 'inline');
                         $('#shop_button').removeClass('disabled');
                         $('#shop_button').removeAttr('disabled');
                     },
            error: function(data) {
                         button.siblings('.addtobasket_failure').css('display', 'inline');
                    }
        });
        

        【讨论】:

          【解决方案5】:
          url = './json/demo_'+var+'.net';
          $.getJSON(url, function(result){
              alert(result[0].name);
          });
          

          $.getJSON('./json/demo_'+var+'.net', function(result){
              alert(result[0].name);
          });
          

          【讨论】:

            猜你喜欢
            • 2012-10-28
            • 1970-01-01
            • 1970-01-01
            • 2011-04-29
            • 1970-01-01
            • 2017-12-11
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多