嵌套的JavaScript使注释系统变慢


nested javascript makes comment system slow

我创建了一个系统,允许用户查看照片并对其进行评论。如果用户单击相册,他将被发送到一个页面,其中第一张照片(带有评论和评论回复)显示在页面中心。在右侧将列出当前相册的所有其他照片。

这部分是用简单的PHP代码完成的,并且伴随着每个新页面加载。

当用户现在单击其中一张照片(列在右侧)时,不会通过 Ajax 加载整个页面,而只会加载相应的元素(照片、评论、评论回复)。

到目前为止,这很有效。以下是相应的代码,以便更好地理解:

.PHP:

// Get data from the database to display the current photo and its comments on the page
// Some Code
// Here is the included file to get the HTML for the comments --> Problem number 2
// List all the photos of the current album at the right side
$album_id = preg_replace('#[^0-9]#', '', $_GET['id']);
$sql = "SELECT * FROM albums WHERE id='$album_id' LIMIT 1";
$user_query = mysqli_query($db_conx, $sql);
while ($row = mysqli_fetch_array($user_query, MYSQLI_ASSOC)) {
    $u = $row['user'];
}
$sql = "SELECT DISTINCT * FROM photos WHERE album_id='$album_id'"; 
$query = mysqli_query($db_conx, $sql);
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
    $id = $row['id'];
    $filename = $row['filename'];
    $style_list_right .= '<div id="right_'.$id.'" onclick="getPhotos('''.$album_id.''','''.$id.''','''.$u.''')">';
    $style_list_right .=     '<img src="'.USERFILES . $u.'/'.$filename.'" />';
    $style_list_right .= '</div>';
}

如果用户点击照片,函数getPhotos()将被调用

function getPhotos(album,photo,user){
    var ajax = ajaxObj("POST", "path/some_php_file.php");
    ajax.onreadystatechange = function() {
        if(ajaxReturn(ajax) == true) {
            // Get a string from PHP delimited by |
            var photo = ajax.responseText.split("|");
            // Change the HTML to display the photos
            // Call the Function to get the comments
            getComments(photo);
        }
    }
    ajax.send("show=photos&photo="+photo);
}
function getComments(photo) {
    var ajax = ajaxObj("POST", "path/some_php_file.php");
    ajax.onreadystatechange = function() {
        if(ajaxReturn(ajax) == true) {
            // Get a string from PHP delimited by |
            var comments = ajax.responseText.split("|||");
            for (var i = 0; i < comments.length; i++){ 
                var comment = comments[i].split("|");
                if(comment[1] == "<?php echo $log_username; ?>") {      // If the user is the author of the comment
                    // Change the HTML of the comments
                    _('comment_'+photo).innerHTML += '<?php echo $comments_html; ?>';    // This is for problem number 2
                    // Call the Function to get the replies of the comment
                    getReplies(comment[0]);    // Send the ID of the comment
                }
            }
        }
    ajax.send("show=comments&photo="+photo);
}
function getReplies(commentID) {
    var ajax = ajaxObj("POST", "path/some_php_file.php");
    ajax.onreadystatechange = function() {
        if(ajaxReturn(ajax) == true) {
            // Get a string from PHP delimited by |
            var replies = ajax.responseText.split("|||");
            for (var i = 0; i < replies.length; i++){ 
                var reply = replies[i].split("|");
                if(reply[1] == "<?php echo $log_username; ?>") {        // If the user is the author of the reply
                    // Change the HTML of the replies
                    _('reply_'+ commentID).innerHTML += '<?php echo $replies_html; ?>';    // This is for problem number 2
                }
            }
        }
        ajax.send("show=replies&commentID="+commentID);
    }
}

some_php_file.php:

// Ajax calls this to load the clicked Photo --> getPhotos()
if (isset($_POST["show"]) && $_POST["show"] == "photos"){
    $picstring = "";
    $photo_id = preg_replace('#[^0-9]#', '', $_POST["photo"]);
    $sql = "...";
    $query = mysqli_query($db_conx, $sql);
    while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
        $filename_1 = $row["..."];
        $filename_2 = $row["..."];
        $photoname = $row["..."];
        $picstring .= "$filename_1|$filename_2|$photoname|||";
    }
    mysqli_close($db_conx);
    $picstring = trim($picstring, "|||");
    echo $picstring;
    exit();
}
// Ajax calls this to load the comments of the clicked photo --> getComments()
if (isset($_POST["show"]) && $_POST["show"] == "comments") {
    $commentstring = "";
    $photo_id = preg_replace('#[^0-9]#', '', $_POST["photo"]);
    $sql = "...";
    $query = mysqli_query($db_conx, $sql);
    while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
        $commentid = $row["..."];
        $author = $row["..."];
        $postdate = $row["..."];
        $avatar = $row["..."];
        $user_image = '<img src="'.USERFILES.$author.'/'.$avatar.'" />';
        $data = $row["..."];
        $data = nl2br($data);
        $data = str_replace("&amp;","&",$data);
        $data = stripslashes($data);
        $statusDeleteButton = '';
        if($author == $log_username) {      //  || $account_name == $log_username
            $statusDeleteButton = '...';
        }
        $commentstring .= "$commentid |$author|$data|$postdate|$user_image|$statusDeleteButton|||";
    }
    mysqli_close($db_conx);
    $commentstring = trim($commentstring, "|||");
    echo $commentstring;
    exit();
}
// Ajax calls this to load the replies of the comments --> getReplies()
if (isset($_POST["show"]) && $_POST["show"] == "replies") {
    $commentstring = "";
    $comment_id = preg_replace('#[^0-9]#', '', $_POST["comment"]);
    // GATHER UP ANY STATUS REPLIES
    $status_replies = "";
    $sql = "...";
    $query_replies = mysqli_query($db_conx, "...");
    $query_replies = mysqli_query($db_conx, $sql);
    $replynumrows = mysqli_num_rows($query_replies);
    if($replynumrows > 0) {
        while ($row = mysqli_fetch_array($query_replies, MYSQLI_ASSOC)) {
            $replyid = $row["…"];
            $replyauthor = $row["..."];
            $replydata = $row["..."];
            $avatar = $row["…"];
            $user_image = '<img src="'.USERFILES.$replyauthor.'/'.$avatar.'"/>';
            $replydata = nl2br($replydata);
            $replypostdate = $row["..."];
            $replydata = str_replace("&amp;","&",$replydata);
            $replydata = stripslashes($replydata);
            $replyDeleteButton = '';
            if($replyauthor == $log_username) { 
                $replyDeleteButton = '…';
            }
            $commentstring .= "$replyid|$replyauthor|$replydata|$replypostdate|$user_image|$replyDeleteButton|||";
        }
    }
    mysqli_close($db_conx);
    $commentstring = trim($commentstring, "|||");
    echo $commentstring;
    exit();
}

问题1:

在我看来,这个变体不是很快.特别是嵌套的Javascript和不断的数据库查询对我来说非常尴尬,而且不是很及时。

所以问题是是否有任何建议来优化代码的结构或代码本身。也许还有一种更模块化的方法可以做到这一点。

问题2:

下一个问题是注释的HTML构造在Javascript和PHP中几乎相同(变量除外)。因此,对我来说,创建一个包含注释 HTML 的文件是合乎逻辑的。现在PHP和Javascript可以使用相同的文件来构造注释及其回复。

包括.php:

$variable = "";
if (IS_AJAX) {
    $user = ''+variable[0]+'';
    $content = ''+variable[1]+'';
}
$variable .= '<div>';
$variable .=     '<a href="'.$user.'">'.$user.'</a>';
$variable .=        '<div><p>'.$content.'</p></div>';
$variable .= '</div>';

问题是,如果 ajax 函数使用这个文件,则必须更改 Javascript 的 PHP 变量。因此,我尝试了以下方法。

some_php_file.php:

$ajax = 0;
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
    $ajax = 1;
}
define('IS_AJAX',$ajax);

但这行不通。因为我读过这可能是由于服务器或我使用 MAMP 的信息。你对我有什么解决方案吗?

我认为在从服务器获取数据时应该使用 json 结构(http://php.net/manual/en/function.json 编码.php),这应该避免您以后必须在 js 中做的任何"拆分"事情,并且还有其他额外的优势。也看看 http://api.jquery.com/jQuery.getJSON/。另外,当您加载页面中的所有图像时:

   $style_list_right .= '<div id="right_'.$id.'"    onclick="getPhotos('''.$album_id.''','''.$id.''','''.$u.''')">';
    $style_list_right .=     '<img src="'.USERFILES . $u.'/'.$filename.'" />';
    $style_list_right .= '</div>';

你可能可以做到:

    $style_list_right .=     '<img src="'.USERFILES . $u.'/'.$filename.'" filename=$filename photoname="$photoname" albimid="$album_id" onclick="getPhotos(this)"/>';
因此,

您在第一次获取中拥有所有信息,因此当您单击它时,您可以从 image 属性中获取这些详细信息(并且根本不进行 ajax 调用)。因此,您只需要一个 ajax 调用即可获取注释。 此外,只返回数据(没有html标记)对ajax响应也有好处,因为从服务器获取的数据量较少,这使得ajax响应更快,然后您可以在客户端中使用js更快地在数据周围添加这些标记。希望这有所帮助。