将3个功能合并在一起

时间:2012-09-02 20:06:07

标签: javascript jquery ajax json

我正在尝试将这三个函数合并在一起,这样我就可以将所有数据放入流中,它将显示在单独的div中。我该怎么做?

AJAX它不会获得用户的第一个,中间名或姓氏,因为它在response.users而不是response.stream

下返回
 <script type="text/javascript">
$(function() 
{
$('.load_more').live("click",function() 
{
var ID = $(this).attr("id");
if(ID)
{
$("#load"+ID).html('Loading...');

$.ajax({
type: "POST",
url: "include/load_more_home_posts.php",
cache: false, 
dataType: "json",
data: { streamitem_id: ID},
cache: false,
success: function(response){
     $.each(response.streams, function(i, stream) {
    $("#articles").prepend("<div id='divider-"+stream['streamitem_id']+"'><div class='userinfo'><a href='/profile.php?username="+stream['username']+"'><img class='stream_profileimage' style='border:none;padding:0px;display:inline;' border=\"0\" src=\"imgs/cropped"+stream['id']+".jpg\" onerror='this.src=\"img/no_profile_img.jpeg\"' width=\"40\" height=\"40\" ></a><div class'delete' style='cursor:pointer;position:relative;top:0px;float:right;padding-right:5px;' onclick=\"delete_('"+stream['streamitem_id']+"');\">X</div><a href='/profile.php?username="+stream['username']+"'>"+stream['first']+" "+ stream['middle']+" "+stream['last']+"</a><span class='subtleLink'> said</span><br/><a class='subtleLink' style='font-weight:normal;'>"+stream['streamitem_timestamp']+"</a><hr>"+stream['streamitem_content']+"<div style='height:20px;' class='post_contextoptions'><div id='streamcomment'><a style='cursor:pointer;' id='commenttoggle_"+stream['streamitem_id']+"' onclick=\"toggle_comments('comment_holder_"+stream['streamitem_id']+"');clearTimeout(streamloop);swapcommentlabel(this.id);\">Write a comment...</a></div><div id='streamlike'><a title='Like "+stream['first']+" "+ stream['middle']+" "+stream['last']+"s status' id='likecontext_"+stream['streamitem_id']+"' style='cursor:pointer;' onClick=\"likestatus("+stream['streamitem_id']+",this.id);\"><div style='width:50px;' id='likesprint"+stream['streamitem_id']+"'>Like</a></div><div style='width:50px;' id='likesprint"+stream['streamitem_id']+"'><a title='See who likes "+stream['first']+" "+ stream['middle']+" "+stream['last']+"s status' href='include/likes.php?streamitem_id="+stream['streamitem_id']+"' /></a></div></div></form></div><div id='streamdislike'><a id='dislikecontext_"+stream['streamitem_id']+"' style='cursor:pointer;' onClick=\"dislikestatus("+stream['streamitem_id']+",this.id);\"><div style='width:70px;' id='dislikesprint"+stream['streamitem_id']+"'>Dislike</a></div><div style='width:70px;' id='dislikesprint"+stream['streamitem_id']+"'></div></div></form><div class='stream_comment_holder' style='display:none;' id='comment_holder_"+stream['streamitem_id']+"'><div id='comment_list_"+stream['streamitem_id']+"'></div><div class='stream_comment_inputarea'><form id='mycommentform' method='POST'  class='form_statusinput'>\
<input type='hidden'  name='streamidcontent' id='streamidcontent' value='"+stream['streamitem_id']+"'>\
<input type='input' name='commentingcontents' id='commentingcontents' placeholder='Say something' autocomplete='off'>\
<input type='submit' id='button' value='Feed'><br/></div></div>").show();

      // the rest of your code from inside your $.each() here
   });
};


  // Comments
    $.each(response.comments, function(i, comment) {

    });

 // Users
    $.each(response.users, function(i, user) {    
    });

// remove the previous load more link
$("#load"+ID).remove();
}
});
}
return false;
});
});
</script>

我需要将3个json对象发送回所有内部的1个div中,这样我才能得到UNDEFINED。

$following_string = mysqli_real_escape_string($mysqli,$_SESSION['id']);
$call="SELECT * FROM streamdata WHERE streamitem_id < '$lastID' AND streamitem_target=".$following_string." OR streamitem_creator=".$following_string." ORDER BY streamitem_id DESC LIMIT 10";
$chant = mysqli_query($mysqli, $call) or die(mysqli_error($mysqli));
$json = array();
$json['streams'] = array();

while ($resultArr = mysqli_fetch_assoc($chant)) {
    $arr = array();
    $arr['streamitem_id'] = $resultArr['streamitem_id'];
    $arr['streamitem_content'] = $resultArr['streamitem_content'];
    $arr['streamitem_timestamp'] = Agotime($resultArr['streamitem_timestamp']);

    $json['streams'][] = $arr;
}

/***** COMMENTS *****/
$check = "SELECT comment_id, comment_datetime, comment_streamitem, comment_poster, comment_content FROM streamdata_comments WHERE comment_poster=".$following_string."  ORDER BY comment_datetime DESC";
$check1 = mysqli_query($mysqli,$check);
$json['comments'] = array();

while ($resultArr = mysqli_fetch_assoc($check1)) {
    $arr = array();
    $arr['comment_id'] = $resultArr['comment_id'];
    $arr['comment_content'] = $resultArr['comment_content'];
    $arr['comment_poster'] = $resultArr['comment_poster'];
    $arr['comment_datetime'] = Agotime($resultArr['comment_datetime']);
    $arr['comment_streamitem'] = $resultArr['comment_streamitem'];

    $json['comments'][] = $arr;
}

/***** USERS *****/

$check = "SELECT * FROM users WHERE id=".$following_string."";
$check1 = mysqli_query($mysqli,$check);
$json['users'] = array();

while ($resultArr = mysqli_fetch_assoc($check1)) {
    $arr = array();
    $arr['username'] = $resultArr['username'];
    $arr['id'] = $resultArr['id'];
    $arr['first'] = $resultArr['first'];
    $arr['middle'] = $resultArr['middle'];
    $arr['last'] = $resultArr['last'];

    $json['users'][] = $arr;
}


echo json_encode($json);
}
?>

1 个答案:

答案 0 :(得分:0)

您需要做的是将commentsusers数据转换为一种格式,您可以轻松查找与您的信息流相关的评论和用户。就像现在一样,您必须遍历comments中的每个评论对象,以查找与您的信息流相关的评论,然后通过users中的每个用户查找与您的评论相关的用户。这不仅效率低,而且代码密集。

要解决此问题,您应该发送带有键的对象,而不是在JSON中发送平面数组,以帮助您查找。换句话说,而不是你的JSON看起来像这样:

{
    "streams": [...],
    "comments": [...],
    "users": [...]
}

看起来应该更像这样:

{
    "streams": [...],
    "comments": {
        943: [...], /* 943 is the ID of the stream */
        945: [...],
        975: [...],
    },
    "users": {
        34: { ... }, /* these keys are user IDs */
        45: { ... },
        398: { ... },
    },
}

甚至可以将您的评论嵌入与它们相关的流对象中:

{
    "streams": [
        { 
            ...,
            "comments": [...]
        },
        { 
            ...,
            "comments": [...]
        },
    ],
    "users": {
        34: { ... }, 
        45: { ... },
        398: { ... },
    },
}

使用这些结构,在处理流时,更容易找到所需的数据。

最好是PHP以这种更理想的格式生成数据。我不是PHP专家,因此我将向您展示如何在JavaScript中转换数据。在循环流对象之前,预处理其他数组以便更容易地进行数据查找:

var commentLookup = {};
var userLookup = {};

$.each(response.comments, function(i, comment) {
    var streamId = comment.comment_streamitem;
    if (!(streamId in commentLookup)) {
        commentLookup[streamId] = [];
    }
    commentLookup[streamId].push(comment);
});

$.each(response.users, function(i, user) {
    userLookup[user.id] = user;
});

现在,当您循环浏览流时,您可以轻松查找相关对象:

$.each(response.streams, function(i, stream) {

    // Output stream content

    // Output comments
    $.each(commentLookup[stream.streamitem_id], function(i, comment) {
        // Output comment contents

        var commenter = userLookup[comment.comment_poster];
        var name = commenter.first + ' ' + commenter.last;
        // etc.
    });

});