如何将输出从php重定向到html


How to redirect output from php to html?

如果这是重复的,我提前道歉,但我搜索了stackoverflow,没有发现任何关于这个主题的内容。在我的base.html中,我有一个这样的表单:

<form method="post" action="../php/base.php">
   <input type="hidden" name="addToDB" value="addToDB" />
   <input type="text" id="name" name="name" placeholder="Enter name">
   <input type="text" id="address" name="address" placeholder="Enter address">
   <button type="submit">Submit</button>
</form>

注意一个伪input元素;它将在PHP中用于针对此表单(这是一个好的做法吗?)base.php具有以下功能:

if (isset($_POST['addToDB'])) {
    create_tables(); // creates tables in DB
    addToDB(); // inserts content to DB
}
function addToDB() {
try {
    // open DB connection
    $db = new PDO("sqlite:../db/mydb.sqlite");
    $name= $_POST['name'];
    $address= $_POST['address'];
    $db->exec("INSERT INTO Person (P_Name, P_Address) VALUES ('$name', '$address');");
    // The following needs to be redirected back to base.html:
    print "<table border=1>";
    print "<tr><td>Name</td><td>Address</td></tr>";
    $result = $db->query('SELECT * FROM Person');
    foreach($result as $row)
    {
        print "<tr><td>".$row['P_Name']."</td>";
        print "<td>".$row['P_Address']."</td></tr>";
    }
    print "</table>";
}catch(PDOException $e)
  {
      echo $e->getMessage();
  }
}

单击提交按钮后,文件base.php将打开并显示一个表。相反,我希望执行base.php中的脚本,并将输出发送回base.html,它将在那里显示(内容div内的某个位置)。

  • 我知道我可能需要使用AJAX,但我不知道如何调用外部PHP文件中的特定函数,并将其返回值(可能是一个带有HTML标记的字符串,用于构造table)重定向回HTML文件(base.html
  • 我使用SQLite进行数据存储;使用create_tables();创建数据库
  • 我是PHP的新手,任何意见/建议都将不胜感激

谢谢

您可以使用HTML、jQuery AJAX和PHP尝试以下操作:

HTML:

<form method="post"  id="formid">
   <input type="hidden" name="addToDB" value="addToDB" />
   <input type="text" id="name" name="name" placeholder="Enter name">
   <input type="text" id="address" name="address" placeholder="Enter address">
   <!-- take simple button -->
   <button type="button" id="submit">Submit</button>
</form>
    <div id="response"></div> 

JavaScript:

<script type="text/javascript">
  $(document).ready(function(){
      //on click of submit button
      $("#submit").click(function(){
          $.ajax({
              url:"../php/base.php",
                  data:{
                          addToDB:"addToDB",
                          name:$("#name").val(),
                          address:$("#address").val()
                       },
                          type:"POST",
                          success:function(res){
                          $("#response").html(res);
                       }
             });
       });
 });
</script>

不会对您的PHP进行任何更改。祝你好运。

I want the ... output sent back to the base.html

那你为什么不在里面处理呢。

form.php

<?php
//  you can save this two functions in a file 'DBhelper.php';
//  then you can 'require(DBhelper.php') here to make this file a little cleaner
//  function create_tables(){
//     put your codes here...
//  }; 
function addToDBandGetAllUsers($name,$address) {
try {
    // open DB connection
    $db = new PDO("sqlite:../db/mydb.sqlite");
    $db->exec("INSERT INTO Person (P_Name, P_Address) VALUES ('$name', '$address');");
    //The following needs to be redirected back to base.html:
    $result = $db->query('SELECT * FROM Person');
    // this data is for test, even the 1 + 1 solution, I will test it, I don't want to post codes in community with errors....
    // $result = array(
    //  array('P_Name' => 'John','P_Address' => 'Foobar'),
    //  array('P_Name' => 'Alex','P_Address' => 'Qux')
    //  );
    // array_push($result, array('P_Name' => $name,'P_Address' => $address));
    return $result;
}catch(PDOException $e)
  {
     echo $e->getMessage();
  }
}
// if the $_POST['name'] is not empty, we will update db
// this is just a basic validation, if we use isset() instead of empty(),
// the form can be submitted with a empty value;
if (! empty($_POST['name']) && ! empty($_POST['address']) ){
    create_tables(); // creates tables in DB
    // I change the the function name , since this guy do a lot of things.... 
    $result = addToDBandGetAllUsers($_POST['name'],$_POST['address']);
} else{
    echo 'Please fill the form.';
} 

?>
<!DOCTYPE html>
<html>
<head>
    <title>form</title>
</head>
<body>
// if we got $result, that means the form has been submitted, so we can display the table;
<?php if (isset($result)) :
    echo '<h1>All users:</h1>';
    print "<table border=1>";
    print "<tr><td>Name</td><td>Address</td></tr>";
    foreach($result as $row)
    {
        print "<tr><td>".$row['P_Name']."</td>";
        print "<td>".$row['P_Address']."</td></tr>";
    }
    print "</table>";
    echo '<hr>';
    endif;
?>
<form method="post" action="form.php">
   <input type="hidden" name="addToDB" value="addToDB" />
   <input type="text" id="name" name="name" placeholder="Enter name">
   <input type="text" id="address" name="address" placeholder="Enter address">
   <button type="submit">Submit</button>
</form>
</body>
</html>

form元素的"action"是其自身。

您可以更改base.html文件,如下所示:

<form method="post" action="../php/base.php" id="formid" onsubmit='return false;'>
       <input type="hidden" name="addToDB" value="addToDB" />
       <input type="text" id="name" name="name" placeholder="Enter name">
       <input type="text" id="address" name="address" placeholder="Enter address">
       <button type="submit" id="submit">Submit</button>
 </form>
 <div id="display"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("#submit").on("click",function(e){
        e.preventDefault();
        var formdata=$("#formid").serialize();
        var url=$("#formid").attr("action");
        $.post(url,formdata,function(data){
         $("#display").html(data);   
        },'json');
    });
});
</script>

这可能对你有帮助。