与 undefined 比较的 typeof 错误 - 数据为空

typeof error comparing to undefined - data is null

我有一些代码对我来说是一个错误 - 我似乎无法找到绕过它的方法或在 javascript 中找到好的解决方案。

        var data = new FormData();

        $.each(files, function(key, obj)
        {
            data.append(obj.name, obj.file);
        });

        data.append('submitCustomizedDatas', 1);
        data.append('ajax', 1);
    $.ajax({
        url: $('#customizationForm').attr('action'),
        type: 'POST',
        data: data,
        cache: false,
        dataType: 'json',
        processData: false,
        contentType: false,
        async: false,
        success: function(data, textStatus, jqXHR)
        {
            if(typeof data.errors === 'undefined')
            {
                $.each(files, function(key, obj)
                {
                    $('input[name="'+obj.name+'"]').addClass('filled');
                    previewFile($('input[name="'+obj.name+'"]'), obj.file);

                });
                $('.uploadingfiles').text('Upload Complete!');
            }
            else
            {
               $('.uploadingfiles').text('Error while uploading, please refresh the page and try again');
            }
            $('.myoverlay').click(function(){$(this).remove()});
        },
        error: function(jqXHR, textStatus, errorThrown)
        {
           $('.uploadingfiles').text('ERRORS: ' + errorThrown);
            $('.myoverlay').click(function(){$(this).remove()});
        }
    });

这用于在我正在制作的网站上上传文件。

Ajax 的这一点在成功时会在 JS 控制台中引发错误。错误是在这一行说 'data is null':

if(typeof data.errors === 'undefined')

只是好奇这看起来是否正确,或者我是否遗漏了一些非常明显的东西。

在javascript、the opening brace placement matters。由于左大括号的位置,您的代码可能并不像您认为的那样。

此外,.success 和 .error 的使用已被弃用。 Consider using .done or .fail methods.

Typeof null returns 一个对象,因此如果 data.errors 为 null,您的检查将失败。考虑做

if (!data.errors) {
    ...
}

最后,从服务器返回的数据可能为空。这将导致您看到的空异常。您可以调试您的应用程序以查看是否属于这种情况。

您描述的错误 "data is null..." 非常准确。当您尝试从 null 对象访问 属性 时,JavaScript 会抛出错误。在这种情况下,您正在尝试访问 data 对象的 errors 属性,在这种情况下是 null(您的服务器未返回任何内容)。

您可能应该在做出任何其他假设之前验证数据对象:

success: function(data, textStatus, jqXHR) {
    if (data !== null) { // first make sure data is not null
        if(typeof data.errors === 'undefined') { // then you can safely trust this line
            // ...
        }
    }
    // ...
}

观看 jqXHR.status 可能是了解您的服务器正在发生的事情的一种方式。

编辑: 事实上,我建议始终使用服务器响应的状态代码来检查错误:

success: function(data, textStatus, jqXHR) {
    if (jqXHR.status === 200) { // 200 - Success
        // Everything went well
        // ...
    } else {
        // Something went wrong
        // console.log(textStatus);
        if (data !== null) { // first make sure data is not null
            if(typeof data.error !== 'undefined') { // // check if the server has returned any error information
                // handle specific error
                // console.log(data.error);
                // ...
            }
        }
    }
}

希望对您有所帮助!