无法从JSON读取未定义的属性(阅读“长度”)显示

ggazkfy8  于 2023-08-08  发布在  其他
关注(0)|答案(1)|浏览(99)

当我尝试从JSON输出数据时,我会得到这个错误:
无法读取undefined的属性(阅读'length')
这是我用于获取数据API JSON的代码:

<script>
var myArray = []

$.ajax({
        method:'GET',
        url:'https:/*****/api/customer/',
        success:function(response){
            myArray = response.data
            buildTable(myArray)
            console.log(myArray)
        }
    })
    
    function buildTable(data){
        var table = document.getElementById('myTable')

        for (var i = 0; i < data.length; i++){
            var row = `<tr>
                            <td>${data[i].nama}</td>
                            <td>${data[i].uid}</td>
                            <td>${data[i].pos}</td>
                      </tr>`
            table.innerHTML += row

        }
    }
</script>

字符串
这是JSON表单:

[
  {
    "nama": "Mei Nurmita Sari, Amd.Keb",
    "uid": "288-028-23072015",
    "pos": "Director",
    "hp": "",
    "fb": "Mei",
    "ig": "meinu",
    "area": "Kalianda Lampung Selatan ",
    "alamat": "Kalianda-lampung selatan"
  },
  {
    "nama": "Rahma Dhania",
    "uid": "288-334-16092017",
    "pos": "Manager",
    "hp": "081297",
    "fb": null,
    "ig": null,
    "area": null,
    "alamat": "Balikpapan"
  },


有什么发现我的长度有错误吗?

gdrx4gfi

gdrx4gfi1#

只是传递你的回应并处理它。它没有data属性。
由于response.data给出了undefined,而我们正在调用undefined.length,因此它会抛出错误“Cannot read properties of undefined(阅读'length')”

$.ajax({
    method: 'GET',
    url: 'https://jsonplaceholder.typicode.com/users',
    success: function(response) {
        buildTable(response)
    }
 })

 function buildTable(data) {
    var table = document.getElementById('myTable')

    for (var i = 0; i < data.length; i++) {
        var row = `<tr>
                            <td>${data[i].name}</td>
                            <td>${data[i].username}</td>
                            <td>${data[i].address.city}</td>
                      </tr>`
        table.innerHTML += row
    }
 }

个字符

相关问题