简体   繁体   English

在Javascript循环中显示JSON数据

[英]Displaying JSON data in Javascript loop

I am having an issue displaying json data. 我在显示json数据时遇到问题。 I have searched and found many examples, but for some reason I get the "Cannot read property 'length' of undefined" error, because "var object = notes.data;" 我已经搜索并找到了许多示例,但是由于某种原因,我收到“无法读取未定义的属性'length'的未定义”错误,因为“ var object = notes.data;”。 comes back as undefined. 返回未定义。

Why is object undefined? 为什么对象未定义? From everything I can see I am doing it right. 从我能看到的一切来看,我做对了。

My json that is returned. 返回的我的json。

{  
   "data":[  
      {  
         "NumberOfAnswers":25,
         "Answer":"51-89 Percent of all items in section are <b>IN STOCK<\/b>",
         "Percent":54.35
      },
      {  
         "NumberOfAnswers":21,
         "Answer":"90-100 Percent of all items in section are <b>IN STOCK<\/b>",
         "Percent":45.65
      }
   ]
}

And here is the function to display it. 这是显示它的功能。 (With some debugging code as well) (以及一些调试代码)

 function format(notes) {
     console.log(notes); //this displays the json
     var object = notes.data;
     console.log(object);
     var i;
     for (var i = 0; i < object.length; i++) {
         var Result = object[i];
         var Answer = Result.Answer;
         console.log(Answer)
     }

  }

Here is the ajax function: 这是ajax函数:

 $.ajax({
     type: 'post',
     url: '/rmsicorp/clientsite/pacingModal/surveyajax2.php',
     success: function(result) {
         if (row.child.isShown()) {
             row.child.hide();
             tr.removeClass('shown');
             detailsrows.splice(RowID, 1);
         } else {
             row.child(format(result)).show();
             tr.addClass('shown');
             if (RowID === -1) {
                 detailsrows.push(tr.attr('id'));
             }

         }
     }
 });

Most likely, the response is still in string format. 响应很可能仍然是字符串格式。 You can add JSON.parse to convert it to an object and then be able too access the data property. 您可以添加JSON.parse以将其转换为对象,然后也可以访问data属性。

Try modifying your function like this to see if it fixes the problem. 尝试像这样修改您的功能,看看是否可以解决问题。

function format(notes) {
   console.log(notes); //this displays the json
   // The following converts the response to a javascript object
   // and catches the exception if the response is not valid JSON
   try {
      notes = JSON.parse(notes);
   } catch(e) {
      console.log('notes is not valid JSON: ' + e);
   }
   var object = notes.data;
   console.log(object);
   var i;
   for (var i = 0; i < object.length; i++) {
      var Result = object[i];
      var Answer = Result.Answer;
      console.log(Answer)
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM