从jquery调用同一页面上的php文件

时间:2014-05-25 02:15:46

标签: php jquery ajax

这可能吗?我想在同一页面上输出isset变量中的内容.. 到目前为止,我已经完成了我的研究,我无法找到解决这类问题的方法。

如何获取isset内的数据,它显示数据,但它将整个页面作为输出。

<?php session_start(); ?>

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script type="text/javascript" src="jquery.10.2.js"></script>
<script type="text/javascript">

$(function(){
    $('.a').click(function(){
        var id = $(this).attr('data-id');
        alert(id);
        $.ajax({
            type: 'post',
            url: 'index.php',
            data:{
                connect: 'try',
                idx : id
            },
            success:function(data){
                $('span').html(data);   
            }
        });
    });
});

</script>
 </head>

<body>

<a href="#" data-id="1" class="a">Click 1</a>
<a href="#" data-id="2" class="a">Click 2</a>
<a href="#" data-id="3" class="a">Click 3</a>
<a href="#" data-id="4" class="a">Click 4</a>


<span></span>
<?php

$con = mysqli_connect("localhost", "root", "", "finance");
if(isset($_POST['connect'])){

    $x = array();
    $data = mysqli_query($con, "SELECT lname FROM tbl_student WHERE id = '$_POST[idx]'");
    while ($row = mysqli_fetch_array($data)) {
        $x[] = $row;

    }
    echo 'this is a test echo';
}
?>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

我不知道为什么你认为你必须使用同一页面;这可能不是一个很好的理由。但我认为这可能是你的想法:

<?php session_start(); ?>
<?php

$con = mysqli_connect("localhost", "root", "", "finance");
if(isset($_POST['connect'])){

    $x = array();
    $data = mysqli_query($con, "SELECT lname FROM tbl_student WHERE id = '$_POST[idx]'");
    while ($row = mysqli_fetch_array($data)) {
        $x[] = $row;

    }
    echo 'this is a test echo';
} else {
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script type="text/javascript" src="jquery.10.2.js"></script>
<script type="text/javascript">

$(function(){
    $('.a').click(function(){
        var id = $(this).attr('data-id');
        alert(id);
        $.ajax({
            type: 'post',
            url: 'index.php',
            data:{
                connect: 'try',
                idx : id
            },
            success:function(data){
                $('span').html(data);   
            }
        });
    });
});

</script>
 </head>

<body>

<a href="#" data-id="1" class="a">Click 1</a>
<a href="#" data-id="2" class="a">Click 2</a>
<a href="#" data-id="3" class="a">Click 3</a>
<a href="#" data-id="4" class="a">Click 4</a>


<span></span>
</body>
</html>
<?php
}
?>