0

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

这部分是用简单的 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 的信息。你对我有什么解决办法吗?

4

1 回答 1

0

我认为从服务器获取数据时应该使用 json 结构(http://php.net/manual/en/function.json-encode.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)"/>';

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

于 2013-09-12T16:12:19.253 回答