【问题标题】:onclick on DIV, load content from database on other divonclick 在 DIV 上,从其他 div 的数据库中加载内容
【发布时间】:2012-10-27 22:30:11
【问题描述】:

我的概念是在 html 中将 div 的内容加载到其他 div 上。简而言之,我想了解新的 Facebook 收件箱是如何工作的,当我们单击右侧的一条消息时,从数据库中获取内容并加载到中心列中。我知道它可能是由某些 AJAX 完成的,但无法弄清楚它是如何实现的。

提前致谢。

【问题讨论】:

标签: php ajax html


【解决方案1】:

如果你使用 jquery,你可以在 div 上使用 onclick 事件。

这就是 HTML/JS 像这样工作。

<!doctype html>
<html>
    <head>
        <title>Document Title</title>
        <script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
        <script>
            $('.clickable').on('click', function(){
                var data_id = $(this).data('id');
                $.ajax({
                    url: 'ajax.php',
                    type: 'POST',
                    data: {id: data_id},
                    dataType: 'json',
                    success: function(data){
                        $('#more-info').html(data.html);
                    },
                    error: function(jqXHR, textStatus, errorThrown){
                        $('#more-info').html('');
                        alert('Error Loading');
                    }
                });
            });

            });
        </script>
    </head>
    <body>
        <div id="item-one" class="clickable" data-id="123">Click me</div>
        <div id="item-two" class="clickable" data-id="456">Click me</div>
        <div id="more-info"></div>
    </body>
</html>

假设我们有一个名为 ajax.php 的 PHP 文件将返回一个 json,就像我们之前在 ajax 函数 dataType: 'json' 中指定的那样,我们正在发送通过 POST 获取 ID,所以这里有一个示例,您必须对其进行处理。

ajax.php

<?php
$id = (int)$_POST['id'];
$query = "SELECT * FROM messages WHERE message_id = {$id} LIMIT 1"; //expecting one row
$result = mysql_query( $query );
$message = mysql_fetch_assoc( $result ); //expecting just on row

$json = array();
$json['html'] = '<p>' . $message . '</p>';

header('Content-Type: application/json');
echo json_encode( $json );
?>

【讨论】:

  • div id 每次都不同。可以一样吗,因为我正在使用 while 循环在右侧面板上加载所有消息。
  • more-info 代表右侧面板,$message 在这种情况下是一条消息,如果您愿意,可以使用 while 循环将这些消息加载到数组中。并在more-info 元素内append 而不是使用$(element).html(val) 使用$(element).append(val) 并使用列表而不是简单的&lt;p&gt;&lt;/p&gt;
  • 我想知道,点击消息后,内容会加载到哪里?
  • success: function(data){ $('#more-info').html(data.html); }, 这将使它加载到id为more-info的元素内
  • 我得到的是正确的:当我点击 data-id 为 123 的“Click Me”时,该 id 被发送到 ajax.php 文件,该文件进行数据库搜索并返回一个 json到 html 页面并将特定消息加载到邮件信息 div 中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-31
  • 1970-01-01
相关资源
最近更新 更多