单击更改 url 而不重新加载


Onclick changing the url without reloading

我有这样的内容:

编辑 ID:

echo '<table>';
$row=mysql_fetch_array($query){
 echo '<tr onclick="window.location=''index.php?id='$row['id']'''"><td>Row1</td></tr>';
 echo '<tr onclick="window.location=''index.php?id='$row['id']'''"><td>Row2</td></tr>';
}
echo '</table>';

当用户按下 tr 时,将显示另一个与 http 请求匹配的表。换句话说,我将在查询中使用 $_GET['id'] 值:

$sql="SELECT * FROM `table` WHERE `id`='".$_GET['id']."'";
$query=mysql_query($sql,$db);
这样,单击

一行时将显示另一个表,其中包含根据用户请求删除的不同数据。它工作正常,但唯一的问题是我必须在不重新加载页面的情况下执行此操作。知道吗?我也需要一些例子,因为我是 Js、Ajax 等的新手。

我的建议是使用数据属性来设置 id。 像这样:

<?php
echo '<table id="aTable">';
 echo '<tr data-id="1"><td>Row1</td></tr>';
 echo '<tr data-id="2"><td>Row1</td></tr>';
echo '</table>';    
echo '<table id="anotherTable">';
echo '</table>';
?>

然后用jQuery捕获点击事件:

<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
    $(document).on('click','#aTable tr', function(e){
        var id = $(this).data('id');
        $('#anotherTable').load('index.php?id='+id);
    });
</script>

在索引中,您可以捕获 id 并使用如下所示的内容回显表:

<?php
    if(isset($_GET['id']) && is_numeric($_GET['id']))
    {
        //DONT USE mysql_*
        $mysqli = new mysqli("localhost", "user", "password", "database");
        if ($result = $mysqli->query("SELECT * FROM `table` WHERE `id`='".(int)$_GET['id']."'")) 
        {
            while ($row = $result->fetch_assoc()) {
                echo '<tr>';
                echo '<td>'.$result['column1'].'</td>';
                echo '<td>'.$result['column2'].'</td>';
                echo '</tr>';
            }       
        }
        //Add an exit because it's an AJAX call.
        exit;
    }
?>

编辑

对于动态数据属性,您可以使用如下内容:

<?php
    echo '<table id="aTable">';
    while($row = mysql_fetch_array($query))
    {
        echo '<tr data-id="'.$row['id'].'"><td>Row1</td></tr>';
    }    
    echo '</table>';
    echo '<table id="anotherTable">';
    echo '</table>';
?>  

通过 Ajax,你可以做这样的事情:

echo '<table>';
 echo '<tr><td><a href="javascript:;" data-id="1" class="load-data">Row1</a></td></tr>';
 echo '<tr><td><a href="javascript:;" data-id="2" class="load-data">Row2</a></td></tr>';
echo '</table>';

然后你的JavaScript将通过jQuery成为这样的内容

<script>
$('.load-data').click(function()
{
    var t = $(this);
    $.ajax({ 
        type: 'POST', 
        url: 'PAGE_TO_GET_DATA',
        data: { 'id': t.data('id') }, 
        success: function(data)
        {
            //based on the response you output to load in the content against ID = x, you can target another DOM element and output to that
            $('#output').html(data);
        }
    });
return false;
});
</script>

在 QUERY 字符串中,清理您的输入,如下所示:

$sql="SELECT * FROM `table` WHERE `id`='".mysql_real_escape_string($_GET['id'])."'";

附言我已经完成了这个半盲,但应该让你走上正确的轨道