首页 > 解决方案 > 未捕获的类型错误:无法读取 null 的属性“forEach”

问题描述

我在 ajax 响应中收到此错误:

    $.ajax({
        type: "GET",
        url: "/search",
        data: {
            s: value,
        },
        success: function (data, textStatus, jqXHR) {
            console.log('data is:', data);
            if (data != null) { 
                    jsonObject = JSON.parse(data);
                    jsonObject.forEach(function (data) { //error here
               // do stuff
            } else {
                console.log('null data received');
            }

但我总是得到这个错误:

data is: null
projects.js:23 Uncaught TypeError: Cannot read property 'forEach' of null
    at Object.success (projects.js:23)
    at c (jquery-3.5.1.min.js?1624781025:2)
    at Object.fireWith [as resolveWith] (jquery-3.5.1.min.js?1624781025:2)
    at l (jquery-3.5.1.min.js?1624781025:2)
    at XMLHttpRequest.<anonymous> (jquery-3.5.1.min.js?1624781025:2)

我的查找空数据的条件有什么问题,我该如何解决?

标签: javascriptnull

解决方案


错误说jsonObjectnull.

您正在测试 if datais null

因此data必须null以 JSON 表示,字符串data也是如此。 null

( "null" != null)


推荐阅读