简体   繁体   English

在DIV上单击,从其他div上的数据库中加载内容

[英]onclick on DIV, load content from database on other div

My concept is to load contents of a div on other div in html. 我的概念是在HTML中的其他div上加载div的内容。 In short I want to learn how the new Facebook inbox works, when we click on a message on the right, the contents and fetched from the database and loaded in the center column. 简而言之,我想了解新的Facebook收件箱的工作原理,当我们单击右侧的消息时,其内容将从数据库中提取并加载到中心栏中。 I know its done by some AJAX may be but unable to figure out how it is possible. 我知道某些AJAX可能会完成此操作,但无法弄清楚这是怎么可能的。

Thanks in advance. 提前致谢。

if you are using jquery you can use onclick event on a div. 如果您使用的是jquery,则可以在div上使用onclick事件。

This is the HTML/JS this work like this. 这是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>

and let say we have a PHP file named ajax.php will return a json like we especified before in the ajax function dataType: 'json' and we are sending an ID through POST so here are a example you have to work it on it. 假设我们有一个名为ajax.php的PHP文件,它将返回一个我们之前在ajax函数dataType:'json'中指定的json,并且我们正在通过POST发送ID ,因此这里有一个示例,您需要对其进行处理。

ajax.php 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 );
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM