通过AJAX在HTML中显示PHP表

时间:2015-05-07 06:33:55

标签: javascript php html ajax xmlhttprequest

我正在尝试在网页上显示我的PHP文件中的表,该网页是使用ajax的index.html文件。我是PHP和ajax的新手,所以我目前不知道代码有什么问题。但是我所知道的是,数据没有在javascript文件中通过这一行。

 document.getElementById("divTable").innerHTML=xmlhttp.responseText;

它没有ajax,但我当然需要转到database.php来显示表。我希望它显示在index.html上。另外,我的PHP文件中的删除按钮是否仍然有效?

P.S。我正在使用vi编辑器,因为我目前正在服务器上对此进行编码。然而,它只是为了测试。我是服务器,ajax和PHP的新手,所以请原谅我的错误(如果有的话)。并忽略我的HTML文件中的表格格式。

P.P.S 我不知道任何形式的jQuery,我写的是我目前对AJAX的了解。

<html>
<head>
    <link rel="stylesheet" type="text/css" href="style.css"/>
    <script src="function.js" type="text/javascript"></script>
</head>

<body>
    <form name="infoForm" method="post" onsubmit="return checkFields()"  action="">
            <table>
            <tr>
                    <td>Name:</td>
                    <td><input type="text" name="name" id="name" maxlength="40"></td>
            </tr>
            <tr>
                    <td>Address:</td>
                    <td><textarea maxlength="45" name="address"id="address" ></textarea></td>
            </tr>
            <tr>
                    <td>Phone:</td>
                    <td><input type="text" name="phone" id="phone"  maxlength="20"><br></td>
            </tr>
            <tr>
                    <td>Gender:</td>
                    <td><input checked type="radio" name="gender" id="male" value="Male">Male
                    <input type="radio" name="gender" id="female" value="Female">Female</td>
            </tr>
            <tr>
                    <td>
                            Nationality:
                    </td>
                    <td>
                            <select name="nation">
                              <option value="Singapore">Singapore</option>
                              <option value="Malaysia">Malaysia</option>
                              <option value="Thailand">Thailand</option>
                              <option value="Indoensia">Indonesia</option>
                              <option value="Philippines">Philippines</option>
                            </select>
                    </td>
            </tr>
            <tr>
                    <td></td>
                    <td>
                            <br><input type="reset" value="Cancel">
                            <input type="submit" name="result" value="Submit" onclick="checkFields()"/>
                    </td>
            </tr>
            </table>
    </form>

    <div id="divTable"></div>
 </body>
</html>

这是我的javascript文件,function.js:

function checkFields(){

var name = document.getElementById("name");
var address = document.getElementById("address");
var phone = document.getElementById("Phone");

 if(confirm('Do you want to submit')){
  if(name == null, name == ""||address == null, address == ""||phone == null, phone == ""){
   alert("Please fill in all your details.");
   return false;
  }
  else{
   var page = "database.php";
  var xmlhttp = new XMLHttpRequest();

  if(xmlhttp==null){
   alert("Your browser does not support AJAX!");
   return false;
  }
   xmlhttp.onreadystatechange=function(){
   document.getElementById("divTable").innerHTML=xmlhttp.responseText;
   }
  xmlhttp.open("GET", page, true);
  xmlhttp.send(null);
  }
 }
 else{
  return false;
 }
}

这是我的PHP文件database.php:

<?php
    // Define database parameters //
    DEFINE ('DB_USER' ,'iqwer222');
    DEFINE ('DB_PASSWORD', 'wfwqr');
    DEFINE ('DB_HOST', 'localhost');
    DEFINE ('DB_NAME', 'aqwfvaqf');

    $table_info = "info";

    // Connect to database
    $conn = @mysql_connect (DB_HOST, DB_USER, DB_PASSWORD) OR die ('Could not connect to Database:'. mysql_error());
    @mysql_select_db (DB_NAME) OR die ('Could not select the Database: '.mysql_error());

    // Delete Row
    if(isset($_POST['delete'])){
     $id = $_POST['deleteRow'];
     $query_string = "delete from $table_info where user_id='$id'";
     $result = @mysql_query($query_string);
     }

    //Check if phone no. is duplicate and if not, insert data
    if(isset($_POST['result'])){
    $phone = $_POST['phone'];
    $query_string = "select phone from $table_info where phone='$phone'";
    $result = @mysql_query($query_string);
    $num_row = mysql_num_rows($result);
    if($num_row){
     echo "A same phone number has been found. Please enter a different phone number.";
    }else{
    $query_string = "insert into $table_info(name, address, phone, gender, nation) values('".$_POST['name']."','".$_POST['address']."','".$_POST['phone']."','".$_POST['gender']."','".$_POST['nation']."')";
    $result = @mysql_query($query_string);
     }
    }

    // Display table
    $query_string = "select * from $table_info";
    $result = @mysql_query($query_string);
    $num_row = mysql_num_rows($result);

    if($num_row){
     echo "<table border=1>";
     echo "<tr><th>Name</th><th>Address</th><th>Phone no.</th><th>Gender</th><th>Nationality</th><th>Created</th><th>Modified</th><th>Action</th></tr>";

             while($row = mysql_fetch_array($result)){
             echo "<tr><td>", $row['name'], "</td>";
             echo "<td>", $row['address'], "</td>";
             echo "<td>", $row['phone'], "</td>";
             echo "<td>", $row['gender'], "</td>";
             echo "<td>", $row['nation'], "</td>";
             echo "<td>", $row['createdTime'], "</td>";
             echo "<td>", $row['modifiedTime'], "</td>";
             ?>

            <!--Delete button-->
            <td><form id="delete" method="post" action="">
            <input type="hidden" name="deleteRow" value="<?php echo $row['user_id'] ?>"/>
            <input type="submit" name="delete" value="Delete" onclick="return confirm('Are you sure you want to delete this contact?')"/></td></form></tr>

            <?php
             }
            echo "</table>";
            }
     else{
      echo "0 results";
    }
?>

    <form method="post" action="index.html">
    <input type="submit" name="goBack" value="Back"/>
    </form>

1 个答案:

答案 0 :(得分:2)

考虑到您的database.php文件正在提供正确的数据。

a)错误: -

您没有在表单提交处理程序上使用return false,只需添加return false并且事情对您有用

b)建议

1)您正在附加checkFields()功能2次,一次点击提交按钮,其他表格提交,删除其中一个(使用sumbit)

2)用户在onreadystatechange内回调,你已经完成的回复将会有效,但这个回调被多次调用

       xmlhttp.onreadystatechange=function(){
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
          document.getElementById("divTable").innerHTML=xmlhttp.responseText;
        }
       }

以下示例代码:

    <html>
    <head>
        <link rel="stylesheet" type="text/css" href="style.css"/>
        <script >
        function checkFields(){

    var name = document.getElementById("name");
    var address = document.getElementById("address");
    var phone = document.getElementById("Phone");

     if(confirm('Do you want to submit')){
      if(name == null, name == ""||address == null, address == ""||phone == null, phone == ""){
       alert("Please fill in all your details.");
       return false;
      }
      else{
       var page = "database.php";
      var xmlhttp = new XMLHttpRequest();

      if(xmlhttp==null){
       alert("Your browser does not support AJAX!");
       return false;
      }
       xmlhttp.onreadystatechange=function(){
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
          document.getElementById("divTable").innerHTML=xmlhttp.responseText;
        }
       }
      xmlhttp.open("GET", page, true);
      xmlhttp.send(null);
      }
     }


     return false;
    }
        </script>
    </head>

    <body>
        <form name="infoForm" method="post" onsubmit="return checkFields()"  action="">
                <table>
                <tr>
                        <td>Name:</td>
                        <td><input type="text" name="name" id="name" maxlength="40"></td>
                </tr>
                <tr>
                        <td>Address:</td>
                        <td><textarea maxlength="45" name="address"id="address" ></textarea></td>
                </tr>
                <tr>
                        <td>Phone:</td>
                        <td><input type="text" name="phone" id="phone"  maxlength="20"><br></td>
                </tr>
                <tr>
                        <td>Gender:</td>
                        <td><input checked type="radio" name="gender" id="male" value="Male">Male
                        <input type="radio" name="gender" id="female" value="Female">Female</td>
                </tr>
                <tr>
                        <td>
                                Nationality:
                        </td>
                        <td>
                                <select name="nation">
                                  <option value="Singapore">Singapore</option>
                                  <option value="Malaysia">Malaysia</option>
                                  <option value="Thailand">Thailand</option>
                                  <option value="Indoensia">Indonesia</option>
                                  <option value="Philippines">Philippines</option>
                                </select>
                        </td>
                </tr>
                <tr>
                        <td></td>
                        <td>
                                <br><input type="reset" value="Cancel">
                                <input type="submit" name="result" value="Submit" />
                        </td>
                </tr>
                </table>
        </form>

        <div id="divTable"></div>
     </body>
    </html>