jQuery 中的 Ajax 调用 - 未捕获的类型错误无法读取 null 的属性“错误”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7868981/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 00:23:17  来源:igfitidea点击:

Ajax call in jQuery - uncaught typeerror cannot read property 'error' of null

jqueryajax

提问by Richard James

I am trying to make an ajax call using the below jQuery.

我正在尝试使用下面的 jQuery 进行 ajax 调用。

But I can see in Chrome, i'm getting uncaught typeerror cannot read property 'error' of null. So this stops the class ('success') getting added. Any idea why it's doing this? Do I somehow need to declare 'error'??

但是我可以在 Chrome 中看到,我得到了未捕获的类型错误无法读取 null 的属性“错误”。所以这会阻止类('success')被添加。知道为什么要这样做吗?我是否需要以某种方式声明“错误”?

function submitForm(formData) {
$.ajax({
    type: 'POST',
    url: 'mailer.php',
    data: formData,
    dataType: 'json',
    cache: false,
    timeout: 7000,
    success: function(data) {
        $("form #form_ajax").removeClass().addClass((data.error === true) ? "error" : "success")
        .html(data.msg).fadeIn('fast');

        if ($('form #form_ajax').hasClass('success')) {
            setTimeout("$('form #form_ajax').fadeOut('fast')", 5000);
        }
    },

     error: function(XMLHttpRequest, textStatus, errorThrown) {
        $('form #form_ajax').removeClass().addClass('error')
            .html('<p>There was an ' + errorThrown + 'error due to a ' + textStatus + ' condition.</p>').fadeIn('fast');
    },

    complete: function(XMLHttpRequest, status) {
        $('form')[0].reset();
    }
});
};

Thanks...

谢谢...

回答by SLaks

datais null, probably because your server didn't send any JSON.

datais null,可能是因为您的服务器没有发送任何 JSON。

回答by Royi Namir

edit your code to :

将您的代码编辑为:

    success: function(data) {
 if ( data.error)  alert(data.error);
  alert(data);
     $("form #form_ajax").rem...

and tell me the alert msg (theres 2)

并告诉我警报消息(有 2 个)

EDIT : its not make any sense:

编辑:它没有任何意义:

do this : enter image description here

做这个 : 在此处输入图片说明