【问题标题】:Cannot read property JQUERY array data无法读取属性 JQUERY 数组数据
【发布时间】:2013-02-21 23:09:54
【问题描述】:

我正在尝试验证 data.announce 但我收到此错误“Uncaught TypeError: Cannot read property 'announce' of null”

这是我的代码

php 文件:

  $return = array("msg" => "You'll recive an email with instructions!");
  return json_encode($return);

jquery:

$("form[id='common-handler/register'] #submit").click(function(e) {
        e.preventDefault();
        if(locked == 1)
            return false;
        locked = 1;

        var _form = $(this).closest('form').attr('id');
        $.post("/"+_form, $(this).closest('form').serialize(), function(data) {
            if(!isEmpty(data.announce))
                $("#search_bar").html(data.msg).fadeIn("slow");
            else
                $("form[id='" + _form + "'] p.msg").text(data.msg);
        }, "json");
    });


function isEmpty(str) {
    return (!str || 0 === str.length);
}

【问题讨论】:

  • 1. PHP 文件需要回显结果,而不是返回它。 2.你应该对回显的消息进行json编码,在jquery中,使用$.parseJSON(data)将它变成一个javascript对象。
  • @kennypu #2:如果你提供了 json 数据类型,你就不需要 parseJSON,他已经做到了。

标签: php jquery null


【解决方案1】:

您不能在 PHP 文件中返回数据,除非您将其包含在另一个 PHP 文件中的某个位置,因此您需要通过 JSON 输出获取您的 $.post()

echo json_encode(array("msg" => "You'll recive an email with instructions!"));
exit(0);

【讨论】:

  • 为什么要在退出函数中输入零。
  • @user1681542 - 不会输出错误并停止执行.. 更多信息:php.net/manual/en/function.exit.php
  • 正如我在上面所说的,如果没有“if(!isEmpty(data.announce))”语句,一切都可以正常工作
  • @Anonymous' 如果它工作正常,那么它工作正常。您收到的错误是 data == nullnull 没有 announce 属性。
  • 只需在输出数组中添加“announce”,就可以了!
【解决方案2】:

试试这个:

return $return = json_encode( array( "announce" => array("msg" => "You'll recive an email with instructions!") ) );

【讨论】:

  • 我不想在我的数组中宣布。没有该语句“if(!isEmpty(data.announce))”,一切正常
【解决方案3】:

您没有“announce”作为要返回的数组中的键之一,只有“msg”

你想要:

array("msg" => "You'll recive an email with instructions!", "announce"=>"My announcement");

【讨论】:

  • 注意,它说announce of null,意思是data是null。丢失的announce 属性是他最不担心的。
  • @KevinB 你是对的.. 宣布为空。我不希望它出现在我的数组中。
  • @Anonymous' 不,announce 不为 null,announce 为 undefineddata 为空,表示你的 php 脚本没有返回任何 json。
  • 如果我删除该语句它可以工作..所以 json 由 php 文件返回
【解决方案4】:

尝试改变:

if(!isEmpty(data.announce))

到:

if(null == data.announce)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-13
    • 2019-06-22
    • 1970-01-01
    相关资源
    最近更新 更多