【发布时间】: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,他已经做到了。