我不知道我是怎么做到的,但我想要的是在用户没有朋友时显示一条错误信息。让他们加一些朋友
这段代码的PHP部分在第一个mysql.
中找不到任何结果时返回[false]而不是错误消息。这是我的jquery代码function fetchfriends(){
$.getJSON('sys/classes/core.php?task=fetchfriends&userid='+sessionparts[1], function(data) {
$.each(data, function(key, val) {
if(val.error)
{
$('<div class="myfriendsbar">'+val.error+'</div>').appendTo('#mycontacts');
return false;
}
else
{
$('<div class="myfriendsbar"><div id="friendsimage'+val.to_userid+'" style="width:32px; height:32px; float:left; margin:3px;"></div>'+val.firstname+' '+val.lastname+'<br/>'+val.username+'</div>').appendTo('#mycontacts');
$('#friendsimage'+val.to_userid).css("background-image", "url(http://bonush.com/beta/sys/classes/photofetch.php?pic="+val.to_userid+":9177156176671)");
}
});
});
这是PHP代码
$number_check = mysql_query("SELECT * FROM user_contact WHERE from_userid = '{$this->userid}'");
if(!mysql_num_rows($number_check))
{
$arr = array('error' => "No Friends?<br/>Search above for New users or invite some friends.");
print json_encode($arr);
}
else
{
$friendlook = mysql_query("%PRIVATECODE%");
$row = mysql_fetch_assoc($friendlook);
$rows[] = $row;
print json_encode($rows);
}
在我看来,如果有错误,你不需要返回数据上的each,首先检查是否有错误,然后如果不可用,在它上运行each来打印朋友…
function fetchfriends(){
$.getJSON('sys/classes/core.php?task=fetchfriends&userid='+sessionparts[1], function(data) {
if(data.error)
{
// your data is an array of friends, unless you have an error, then it is no array, so no need for the each to print the error.
$('<div class="myfriendsbar">'+data.error+'</div>').appendTo('#mycontacts');
return false;
}
else
{
//only when data.error does not exist it is filled as an array of friends you return i presume...
$.each(data, function(key, val) {
$('<div class="myfriendsbar"><div id="friendsimage'+val.to_userid+'" style="width:32px; height:32px; float:left; margin:3px;"></div>'+val.firstname+' '+val.lastname+'<br/>'+val.username+'</div>').appendTo('#mycontacts');
$('#friendsimage'+val.to_userid).css("background-image", "url(http://bonush.com/beta/sys/classes/photofetch.php?pic="+val.to_userid+":9177156176671)");
});
}
});
在"error"状态下,JSON结果如下所示:
{
"error": "No friends? ... etc."
}
所以当你做$data.each
时,你会得到一个迭代,其中key
是"error"
, val
是"No friends? ..."
等等。所以,当你执行val.error
时,你访问的是一个字符串的error
属性,这个属性不存在