Onclick更改url而不重新加载

时间:2014-12-15 12:54:23

标签: javascript php http get

我有这样的内容:

编辑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 [&#39; id&#39;]值:

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

通过这种方式,另一个包含用户请求的不同数据的表将在单击一行时显示。它工作正常,但唯一的问题是我必须这样做而不重新加载页面。任何想法?我也需要一些例子,因为我是Js,Ajax等的新手。

2 个答案:

答案 0 :(得分:2)

我的建议是使用数据属性来设置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捕获click事件:

<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>';

?>  

答案 1 :(得分:1)

通过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'])."'";

P.S。我已经完成了半盲,但应该让你走上正轨