如何访问该对象?

时间:2019-06-19 16:23:36

标签: jquery

在控制台中,它显示obj,但是在我尝试访问它的下一行中显示错误:无法读取未定义的属性“ date”。我没弄错是什么。

我尝试了以下操作: console.log(obj [9] .date)

请经历成功:function(obj)

<script type="text/javascript">
  $("#date-picker").flatpickr({
    defaultDate : new Date()
  });

  console.log($("#date-picker").val());

  $("#date-picker").on('change',function(){
      console.log($("#date-picker").val());
      var select_date = $("#date-picker").val();
      console.log("select_date : ",select_date);

      $.ajax({
      type: "POST",
      url: "http://127.0.0.1:8000/attendance/",
      dataType: 'json',
      async: true,
      data: {
        "selected" : '1',  
        "select_date" : select_date,
        csrfmiddlewaretoken : '{{ csrf_token }}'
      },
      success: function(obj){
        console.log("post alerts");
        console.log("success");
        console.log(obj);
        console.log(obj[9].date);

      failure: function(data){
        console.log("failure");
        console.log(data);
      },
    });
  })

 </script>

console.log(JSON.stringify(obj))显示:

{
    "obj": [{
        "student_id": 1,
        "date": "2019-06-20",
        "check_in": "2019-06-19T11:27:52.692Z",
        "check_out": "2019-06-19T11:27:52.693Z",
        "tutor_time": "2019-06-19T11:27:52.693Z",
        "intention": "",
        "absent_present": "",
        "reasonOfAbsence": ""
    }, {
        "student_id": 2,
        "date": "2019-06-20",
        "check_in": "2019-06-19T11:27:52.762Z",
        "check_out": "2019-06-19T11:27:52.762Z",
        "tutor_time": "2019-06-19T11:27:52.762Z",
        "intention": "",
        "absent_present": "",
        "reasonOfAbsence": ""
    }],
    ...
}

2 个答案:

答案 0 :(得分:0)

将此更改:console.log(obj[9].date);更改为此console.log(obj.date[9]);

答案 1 :(得分:0)

该对象具有obj属性,该属性包含学生数组。所以你需要使用

console.log(obj.obj[9].date);

此外,您需要确保obj.obj.length至少为10才能访问索引9,因此请使用

if (obj.obj.length >= 10) {
  console.log(obj.obj[9].date);
}