嵌套的JSON数组对象代码不起作用

时间:2017-04-06 07:02:18

标签: javascript jquery json ajax

我在ajax调用之后的数据中有json对象,如

[
  {
    "_id": {
      "$id": "58d8e2831d7859e80d000033"
    },
    "broadcast_id": 70,
    "studentList": "",
    "employeeList": "999",
    "mailTitle": "adsf",
    "broadcastMessage": "dsfsdf dsd fgd",
    "emailSent": "0",
    "userdetails": []
  },
  {
    "_id": {
      "$id": "58d8eaba1d7859c81300002e"
    },
    "broadcast_id": 72,
    "studentList": "",
    "employeeList": "999|788",
    "mailTitle": "Hekjh",
    "broadcastMessage": "hhyky jk",
    "emailSent": "0",
    "userdetails": []
  },
  {
    "_id": {
      "$id": "58dde8ed1d78597011000029"
    },
    "user_id": 1,
    "broadcast_id": 76,
    "studentList": "",
    "employeeList": "999|788",
    "mailTitle": "Hello",
    "broadcastMessage": "How are u ",
    "emailSent": "0",
    "dateSent": "31/03/2017",
    "userdetails": [
      {
        "_id": {
          "$id": "568f95dc99fbadb016000029"
        },
        "uid": 1,
        "username": "test",
        "password": "LeLafe#7861",
        "email_id": "sales@lelafe.com",
        "creation_date": "",
        "role": "admin",
        "is_enabled": 1
      }
    ]
  }
]

现在我正在尝试解析嵌套的json属性 userdetails ,以便将角色显示在表格中。我试过以下几行

 $.ajax({
         url: 'index.php?action=fetchBroadcastedMessageList',
         type: 'POST',
         dataType: 'JSON',
         data: { usertype: usertype },
         success: function(data) {
             for (var i in data) {
                 $("#broadcastedmessagelist").append('<tr>' +
                     '<td style="text-align: center;">' +
                     '' + data[i].userdetails["role"] + '' +
                     '</td>'...
                 );
             }
         });
 }

data[i].userdetails["role"]行不会检索相应的角色 有用户详细信息的价值。请帮我 !!!

8 个答案:

答案 0 :(得分:2)

您需要一个额外的级别(//Declarations SqlCommand CMD; SqlDataReader Reader; private void Save(string EmplID, double MRate, double HRate, double DRate) { CMD = new SqlCommand("SELECT * FROM tblEmpl WHERE ACTIVE = 1", dbConn.connection); Reader = CMD.ExecuteReader(); while (Reader.Read()) { CMD = new SqlCommand("UPDATE tblEmpl SET MRate = " + MRate + ", HRate = " + HRate + ", DRate = " + DRate + " WHERE EmplID = '" + EmplID + "'", dbConn.connection); CMD.ExecuteNonQuery(); } } ),因为[0]返回一个数组。为此,您必须首先检查数组是否包含元素:

userdetails

也许您希望更早地检查数组长度,以便在数组没有元素时可以完全省略 $("#broadcastedmessagelist").append('<tr>' + '<td style="text-align: center;">' + (data[i].userdetails.length ? data[i].userdetails[0]["role"] : '') + '</td>' ); 。取决于你的期望......

append

答案 1 :(得分:2)

您也可以像这样使用

 $.ajax({
       url: 'index.php?action=fetchBroadcastedMessageList',
       type: 'POST',
       dataType: 'JSON',
       data: {usertype: usertype},
       success: function (data) {
            $.each(data , function(key,value)) {
                       $("#broadcastedmessagelist").append('<tr>' +
                              '<td style="text-align: center;">' +
                              '' + value.userdetails[0]["role"] + '' +
                              '</td>'...
           );
           }
       });  
      }

答案 2 :(得分:1)

而是使用forEach然后只使用该对象。无论如何,这似乎是你想要实现的目标。

Process:               lldb-rpc-server [71615]
Path:                  /Applications/Xcode_8.3.app/Contents/SharedFrameworks/LLDBRPC.framework/Versions/A/Resources/lldb-rpc-server
Identifier:            lldb-rpc-server
Version:               2
Code Type:             X86-64 (Native)
Parent Process:        Xcode [52463]
Responsible:           lldb-rpc-server [71615]
User ID:               506

Date/Time:             2017-04-06 12:28:42.491 +0800
OS Version:            Mac OS X 10.12.4 (16E195)
Report Version:        12
Anonymous UUID:        

Sleep/Wake UUID:       

Time Awake Since Boot: 350000 seconds
Time Since Wake:       3500 seconds

System Integrity Protection: enabled

Crashed Thread:        8  RPC packet thread for client tid 028474a8 (42235048)

Exception Type:        EXC_BAD_ACCESS (SIGSEGV)
Exception Codes:       KERN_INVALID_ADDRESS at 0x0000000000000018
Exception Note:        EXC_CORPSE_NOTIFY

Termination Signal:    Segmentation fault: 11
Termination Reason:    Namespace SIGNAL, Code 0xb
Terminating Process:   exc handler [0]

答案 3 :(得分:1)

应该是

data.userdetails[0].role

答案 4 :(得分:0)

&#13;
&#13;
var data= [{"_id":{"$id":"58d8e2831d7859e80d000033"},"broadcast_id":70,"studentList":"","employeeList":"999","mailTitle":"adsf","broadcastMessage":"dsfsdf dsd fgd","emailSent":"0",
            "userdetails":[]},
     {"_id":{"$id":"58d8eaba1d7859c81300002e"},"broadcast_id":72,"studentList":"","employeeList":"999|788","mailTitle":"Hekjh","broadcastMessage":"hhyky jk","emailSent":"0",
          "userdetails":[]},
     {"_id":{"$id":"58dde8ed1d78597011000029"},"user_id":1,"broadcast_id":76,"studentList":"","employeeList":"999|788","mailTitle":"Hello","broadcastMessage":"How are u ","emailSent":"0","dateSent":"31\/03\/2017",
           "userdetails":[{"_id":{"$id":"568f95dc99fbadb016000029"},"uid":1,"username":"test","password":"LeLafe#7861","email_id":"sales@lelafe.com","creation_date":"",
           "role":"admin",
           "is_enabled":1}]}]
           
           $.each(data,function(i,item){
           if(item.userdetails.length > 0)
           {
           $.each(item.userdetails,function(i,userdetail){
           $("#broadcastedmessagelist").append('<tr>' +'<td style="text-align: center;">' +userdetail.role +'</td>');
           });
           }
           else
           {
           $("#broadcastedmessagelist").append('<tr>' +'<td style="text-align: center;">' +'not available' +'</td>');
           }
           });
           
          
           
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="broadcastedmessagelist">

</table>
&#13;
&#13;
&#13;

答案 5 :(得分:0)

如上所述,您需要额外的级别嵌套。还建议使用es6模板字符串进行更清晰的字符串插值。

data.map((i)=>{
  if(i.userdetails.length >0){
    $("#broadcastedmessagelist")
    .append(`<tr><td style="text-align:center;">${i.userdetails[0].role}</td>`);
  } 
})

答案 6 :(得分:0)

观察 userdetails 是一个数组,以便访问您必须使用的数组中的任何元素,例如 { {1}}

试试这个:

data[i].userdetails[0]["role"]

答案 7 :(得分:-1)

/ *下面的代码将调用index.php,捕获json响应并呈现HTML * /

$.ajax({
  url: 'index.php?action=fetchBroadcastedMessageList',
  type: 'POST',
  dataType: 'JSON',
  data: {usertype: usertype},
  success: function (data) {
 $("#broadcastedmessagelist").append('<tr><td>broadcastMessage</td><td>broadcast_id</td><td>emailSent</td><td>employeeList</td><td>mailTitle</td><td>studentList</td><td>userdetails</td></tr>');
    $.each(data, function(key,value){
      var stringBuilder = '<tr><td>' + value.broadcastMessage + '</td><td>' + value.broadcast_id + '</td><td>' + value.emailSent + '</td><td>' + value.employeeList + '</td><td>' + value.mailTitle + '</td><td>' + value.studentList + '</td>';

      if(value.userdetails.length > 0){
        stringBuilder = stringBuilder + '<td><table border="1"><tr><td>uid</td><td>username</td><td>password</td><td>email_id</td><td>creation_date</td><td>is_enabled</td><td>role</td></tr>';
        $.each(value.userdetails, function(k,v){
          stringBuilder =  stringBuilder + '<tr><td>' + v.uid + '</td><td>' + v.username + '</td><td>' + v.password + '</td><td>' + v.email_id + '</td><td>' + v.creation_date + '</td><td>' + v.is_enabled + '</td><td>' + v.role + '</td></tr>';
        });
        stringBuilder =  stringBuilder + '</table></td>';
      }else{
        stringBuilder =  stringBuilder + '<td></td>';
      }
      stringBuilder =  stringBuilder + '</tr>';
      $("#broadcastedmessagelist").append(stringBuilder);
    });
     }
});