Ajax-PHP没有按预期工作

时间:2013-03-08 04:51:46

标签: php ajax

我正在尝试使用AJAX和PHP构建一个打印出数据库的页面

的index.php

 <div id='mainTable'>
      <table border=1>
            <tr><th class='col1'>Mã Sinh Viên</th>
                <th class='col2'>Họ tên</th>
                <th class='col3'>Ngày sinh</th>
                <th class='col4'>Giới tính</th>
                <th class='col5'>Địa chỉ</th>
            </tr>
    </table>
</div>
<script>
function showPage(page) {
    var xmlhttp;
    if(window.XMLHttpRequest)   {
        xmlhttp= new XMLHttpRequest();
    }
    else    {
        xmlhttp= new ActiveObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()   {
        if(xmlhttp.readystate==4 && xmlhttp.status==200)    {
            $("#mainTable table").append(xmlhttp.responseText);
        }
    }
    xmlhttp.open("GET","showStudent.php?page="+page,true);
    xmlhttp.send();
     }

  $(document).ready(function(){
  showPage(1);
  });
  </script>

showStudent.php

<?php
session_start();
$db= new mysqli("localhost","root","","student");
if(!isset($_GET['page']))   {
    $page=1;
}
else    {
    $page= $_GET['page'];
}
$start= ($page-1)*10;
$result= $db->query("SELECT * FROM information LIMIT $start,10");
while($row= $result->fetch_assoc()) {
    $stuId= $row['stuId'];
    $stuName= $row['stuName'];
    $stuDob= $row['stuDoB'];
    $stuSex= $row['stuDoB']?'Nam':'Nữ';
    $stuAdd= $row['stuAdd'];
    echo    "<tr><td class='col1'>$stuId</td>
            <td class='col2'>$stuName</td>
            <td class='col3'>$stuDoB</td>
            <td class='col4'>$stuSex</td>
            <td class='col5'>$stuAdd</td>
            </tr>
            ";  
    }
$_SESSION['page']= $page;
  ?>

正如我所料,当页面加载时,它必须从数据库打印出一个表,但我只有空白字段。我尝试了另一种使用PHP代码的方法,它起作用,所以我认为问题是关于AJAX。 有人可以帮助我,我的AJAX代码有什么问题吗?

2 个答案:

答案 0 :(得分:1)

替换此部分:

<script>
function showPage(page) {
    var xmlhttp;
    if(window.XMLHttpRequest)   {
        xmlhttp= new XMLHttpRequest();
    }
    else    {
        xmlhttp= new ActiveObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()   {
        if(xmlhttp.readystate==4 && xmlhttp.status==200)    {
            $("#mainTable table").append(xmlhttp.responseText);
        }
    }
    xmlhttp.open("GET","showStudent.php?page="+page,true);
    xmlhttp.send();
     }

  $(document).ready(function(){
  showPage(1);
  });
  </script>

使用:

<script>
function showPage(page) {
    $.get("showStudent.php?page="+page, function(data){
        $("#mainTable table").append(data);
    });
}

$(document).ready(function(){
    showPage(1);
});
</script>

答案 1 :(得分:1)

你有一个错字(或者你做错了)。 xmlhttp.readystate应为xmlhttp.readyState,请注意首都S.还有什么是ActiveObject

相关问题