通过ajax和php动态更新页面

时间:2017-08-10 15:59:04

标签: php html ajax

我想通过ajax将数据提交到数据库,并且在将数据插入数据库之后,这些数据应该在文件 Demo.html 上动态地显示在最后,即在我的情况下为div之后。< / p>

通过ajax存储数据我已经完成但我不知道如何将这个新插入的数据显示到 Demo.html 。所以请指导我如何实现这一点。

以下是我的代码。

AjaxFile.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body >

<p><span id="get">Ajax response comes here</span></p>
<div id="divId">
    <input type="text" name="i1" value=""  /><br />
    <input type="text" name="i2" value=""  /><br />
    <button onclick="ajaxFunction()">Click </button>
</div>

<script src="jquery-3.2.1.min.js" ></script>
<script type="text/javascript">

function ajaxFunction() {
    $(function(){
        var myData1 = $("input[name='i1']").val();
        var myData2 = $("input[name='i2']").val();

        $.ajax({
            type : "post",
            dataType : "text",
            url : "controller.php",
            data : { data1 : myData1, data2 : myData2}, 
            success : function(msg){
                document.getElementById('get').innerHTML = msg;

            }
        });
    });
}

</script>
</body>
</html>

Controller.php这样

<?php

session_start();

$servername = "localhost";
$username = "root";
$password = "";
$databaseName = "mydb1";

 try {

  $conn = new PDO("mysql:host = $servername; dbname = $databaseName", $username, $password);
  // set the PDO error mode to exception
  $conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);

   $conn->exec("use mydb1");

  if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['data1']) && isset($_POST['data2'])) {

      $data1 = $_POST['data1'];
      $data2 = $_POST['data2'];

      $statement = $conn->prepare("Insert into mytable (data1, data2) values (:data1 , :data2)");

      if( $statement->execute(array("data1"=>"$data1", "data2"=>"$data2")) ) {

        echo "successfully inserted";
        // want to display $data1 and $data2 at the last in Demo.html just after inserting.


    } else {
      echo "Not successfully inserted";
    }
} else {

     echo "something is not set";
}

}catch(PDOException $e) {
echo "connection failed ". $e->getMessage();
}

$conn = null;
?>

Demo.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style type="text/css">
    body {
        margin : 0;
    }
    #first {
        width : 100%;
        height : 100px;
        margin : 30px auto auto auto;
        border : 1px dashed black;
    }
</style>
</head>
<body>

<div id="first" align="center"> I want to display newly inserted data below this div</div>

</body>
</html>

3 个答案:

答案 0 :(得分:2)

我的解决方案不涉及php,JQuery&amp; HTML5 LocalStorage,最重要的是它将解决您的问题。

首先,在success ajaxFunction()函数中,您应该将data1data2的值存储在Localstorage个变量中。阅读LocalStorage here

<强> ajaxFunction()

    $.ajax({
        type : "post",
        dataType : "text",
        url : "controller.php",
        data : { data1 : myData1, data2 : myData2}, 
        success : function(msg){
            document.getElementById('get').innerHTML = msg;

            // store your values in LocalStorage
            localStorage.setItem("StoredData1", myData1);
            localStorage.setItem("StoredData2", myData2);

            // redirect after storing 
            window.location.href = 'Demo.html'
        }
    });

然后在 Demo.html 中包含的脚本中或直接在其HTML中编写以下JavaScript代码,以获取我们之前存储的LocalStorage变量并附加到div。

Demo.html中的HTML body

<body>
  <div id="first" class="afterThis" align="center"> I want to display newly inserted data below this div</div>
</body>

Demo.html中的JavaScript

$(".afterThis").last().after("<div class='afterThis'>"+ localStorage.getItem("StoredData1") +"</div>");
$(".afterThis").last().after("<div class='afterThis'>"+ localStorage.getItem("StoredData2") +"</div>");

答案 1 :(得分:1)

插入数据库后使用函数文件()保存到带附加子函数的文件,将新行写入文件,并将读取文件写入demo.html - &lt;但这需要是php文件和php函数来读取你最后插入的数据,然后在ajax中成功简单重定向:section到你的文件,或者例如在你想要的地方读取文件到div。

在你的控制器php中使用函数文件将附加模式字符串保存到你的文件中。看这里:http://php.net/manual/en/function.file-put-contents.php

之后调用ajax来获取php内部的read.php使用php的文件()来读取你之前写过的文件。

答案 2 :(得分:0)

这是基于@Nikhil Nanjappa的答案。

您可以使用数组在localStorage中存储更多项目。 Store object in localStorage

AjaxFile.html

success: function(msg) {
  document.getElementById('get').innerHTML = msg;

  StoredData = JSON.parse(localStorage.getItem("StoredData"));
  if(!StoredData) StoredData = [];
  StoredData.push(myData1);
  StoredData.push(myData2);
  localStorage.setItem("StoredData", JSON.stringify(StoredData));

  window.location.href = 'Demo.html'
}

Demo.html (在正文的底部)

<script type="text/javascript">
  StoredData = JSON.parse(localStorage.getItem("StoredData"));
  StoredData.reverse().forEach( function(data) {
    $('#first').after('<div>data = ' + data +'</div>')
  });
</script>