【问题标题】:Uncaught TypeError: Cannot read property 'message' of undefined未捕获的类型错误:无法读取未定义的属性“消息”
【发布时间】:2014-04-14 04:51:29
【问题描述】:

我正在尝试为我的网站实施 AJAX 联系表单,我遇到的问题是,当我点击提交时,我在 Google Chrome 中收到以下错误:

"Uncaught TypeError: Cannot read property 'message' of undefined----contact-form.js:38".

请找到the HTML codecontact-from.js

【问题讨论】:

  • 您应该使用 JavaScript、Chrome、AJAX 等对其进行标记,以便合适的人看到它。
  • 在访问之前检查“response.responseJSON”值是否为空/未定义:if(response.responseJSON) ....

标签: javascript html ajax google-chrome


【解决方案1】:

错误是因为responseJSON 不是standard propertythat jQuery makes availableXMLHttpRequests。

你会想要use responseText instead,其中may be parsable

contactForm.addAjaxMessage($.parseJSON(response.responseText).message, true);

// or
contactForm.addAjaxMessage(response.responseText, true);

【讨论】:

    【解决方案2】:
    error: function(response) {
         contactForm.addAjaxMessage(response.responseJSON.message, true);
    }
    

    如果你看一下jQuery documentation for error in $.ajax,你会看到回调函数的第三个参数是一个包含错误消息的字符串:

    错误

    Type: Function( jqXHR jqXHR, String textStatus, String errorThrown )

    请求失败时调用的函数。这 函数接收三个参数: jqXHR(在 jQuery 1.4.x 中, XMLHttpRequest) 对象,描述错误类型的字符串 发生和可选的异常对象(如果发生)。

    所以,试试这个吧:

    error: function(a, b, response) {
         // You can use `a` and `b` if you need them.
    
         contactForm.addAjaxMessage(response, true);
    }
    

    【讨论】:

      猜你喜欢
      • 2021-12-22
      • 2015-01-06
      • 2017-07-26
      • 1970-01-01
      • 2019-02-26
      • 2021-12-25
      • 1970-01-01
      相关资源
      最近更新 更多