簡體   English   中英

將用戶輸入保存到PHP,然后在Javascript函數中使用

[英]Saving User Input to PHP to then Use in Javascript Function

尋找解決我遇到的問題的方法。 我的PHP文件能夠根據用戶輸入存儲日期和時間。 但是,一旦存儲了日期,就不再可以在Javascript函數中使用它。

我只是迷路於如何逐步處理數據。 如何提取數據庫中存儲的數據以在Javascript函數中使用?

更新:添加代碼

PHP:僅存儲輸入,並顯示已存儲

    <?php
// ONLY Process Form if $_POST is NOT Empty
if ( ! empty( $_POST ) ) {

  // Connect to MySQL
  $mysqli = new mysqli( 'hn', 'un', 'pw', 'db' );

  // Check Our Connection
  if ( $mysqli->connect_error ) {
    die( 'Connect Error: ' . $mysqli->connect_errno . ': ' . $mysqli->connect_error );
  }

  // Insert Our Data
  $sql = "INSERT INTO table ( mydate ) VALUES ( '{$mysqli->real_escape_string($_POST['myDate'])}' )";
  $insert = $mysqli->query($sql);

  // Print Response from MySQL
  if ( $insert ) {
    echo "Success! Row ID: {$mysqli->insert_id}";
  } else {
    die("Error: {$mysqli->errno} : {$mysqli->error}");
  }

  // Close Connection
  $mysqli->close();
}
?>

HTML:只是一種形式

  <html>
  <head>
    <meta charset="utf-8">
    <title>User Form</title>
  </head>
  <script type="text/javascript" src="/displaytimer.js"></script>
  <body>
    <!-- HTML Form -->
    <form class="" action="/index.php" method="post">
      <input type="datetime-local" name="myDate" id="myDate"><br /><br />
      <button id="submit" onclick="clickButton()" value="submit">Submit</button><br /><br />
      <div id="showDate"></div>
    </form>
   </body>
  </html>

JAVASCRIPT:根據用戶輸入的日期生成一個計時器。 也可以在iPhone上訪問(為此可在SO上找到幫助)。 我敢肯定有一種更簡單的方法可以做到這一點,但是我主要是在尋找如何仍然使用var n中輸入的日期

// get the iso time string formatted for usage in an input['type="datetime-local"']
var tzoffset = (new Date()).getTimezoneOffset() * 60000; //offset in milliseconds
var localISOTime = (new Date(Date.now() - tzoffset)).toISOString().slice(0,-1);
var localISOTimeWithoutSeconds = localISOTime.slice(0,16);

// select the "datetime-local" input to set the default value on
var dtlInput = document.querySelector('input[type="datetime-local"]');

// set it and forget it ;)
dtlInput.value = localISOTime.slice(0,16);

function clickButton() {
  var x = setInterval(function() {
    // Get Date Selected & Convert to ISO
    var n = document.getElementById("myDate").value;
    var d = new Date(n);
    var dISO = d.toISOString();

    // Get Today's Date
    var today = new Date();
    var tS = today.toDateString();
    var tISO = today.toISOString();

    // Calculate Time Left
    var dParse = Date.parse(dISO);
    var tParse = Date.parse(tISO);
    var distance = dParse - tParse;
    // days
    var days = Math.floor(distance / (1000 * 60 * 60 * 24));
    if (days > 0) {
      days = Math.floor(distance / (1000 * 60 * 60 * 24));
    } else {
      days = 0;
    }
    // hours
    var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    if (hours > 0) {
      hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    } else {
      hours = 0;
    }
    // minutes
    var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    if (minutes > 0) {
      minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    } else {
      minutes = 0;
    }
    // seconds
    var seconds = Math.floor((distance % (1000 * 60)) / 1000);
    if (seconds > 0) {
      seconds = Math.floor((distance % (1000 * 60)) / 1000);
    } else {
      seconds = 0;
    }

    // Print Distance or Expired Message
    if (days > 0 || hours > 0 || days > 0 || seconds > 0) {
      document.getElementById("showDate").innerHTML = days + " days " + hours + " hours " + minutes + " minutes " + seconds + " seconds ";
    } else {
      document.getElementById("showDate").innerHTML = "The time has expired";
    }
  }, 1000);
}

通過使用AJAX提交表單(即在服務器上存儲日期),該頁面將不會重新加載,因此您的javaScript代碼將被執行。
以下是其工作方式的分解:

  1. clickButton()JavaScript函數從表單的輸入字段獲取值。
  2. 然后,它執行ajax請求,將數據發送到PHP文件,即store_data.php(其中將包含最初位於頁面頂部的php代碼)。
  3. 服務器處理PHP文件中的內容。 即將日期插入數據庫
  4. PHP文件將您喜歡的任何數據回傳給客戶端(如果您遇到成功或失敗)。
  5. 在客戶端執行回調,可以從服務器檢索(回顯的)數據,並可以執行javaScript代碼。 注意:頁面尚未重新加載,因此myDate輸入字段仍被填充。

的index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>User Form</title>
<script type="text/javascript" src="/displaytimer.js"></script>
</head>
<body>
  <!-- HTML Form -->
  <form class="" action="" method="post">
    <input type="datetime-local" name="myDate" id="myDate"><br /><br />
      <button id="submit" onclick="clickButton()" type="button">Submit</button><br /><br />
      <div id="showDate"></div>
  </form>
</body>
</html>

displaytimer.js

 window.onload = function(){
      // get the iso time string formatted for usage in an input['type="datetime-local"']
      var tzoffset = (new Date()).getTimezoneOffset() * 60000; //offset in milliseconds
      var localISOTime = (new Date(Date.now() - tzoffset)).toISOString().slice(0,-1);
      var localISOTimeWithoutSeconds = localISOTime.slice(0,16);

      // select the "datetime-local" input to set the default value on
      var dtlInput = document.querySelector('input[type="datetime-local"]');

      // set it and forget it ;)
      dtlInput.value = localISOTime.slice(0,16);
    }


    function createXHR(){
      //This function sets up the XMLHttpRequest
      try{
        return new XMLHttpRequest();
      }catch(e){
        //to support older browsers
        try{
          return new ActiveXObject("Microsoft.XMLHTTP");
         }catch(e){
           return new ActiveXObject("Msxml2.XMLHTTP");
         }
      }
    }

    function clickButton(){
      //The form has been submitted.
      //Get the value of the myDate field from the form
      var myDate = document.getElementById('myDate').value;
      //set up the ajax request
      xmlhttp = createXHR();
      xmlhttp.onreadystatechange = ajaxCallback; //name of our callback function here
      //Ive called the php file store_data.php but you can call it whatever you like.
      xmlhttp.open("POST", "store_data.php" ,true);
      xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      //send our variables with the request
      xmlhttp.send("myDate=" + myDate);
    }

    function ajaxCallback(){
      //this function will be executed once the ajax request is completed
      if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
        //The ajax request was successful.
        //we can now get the response text using xmlhttp.responseText. This will be whatever was echoed in the php file
        var data = xmlhttp.responseText; 
        //In your case "data" will either be "Success! Row ID: ..." OR "Error: ....." so you can do checks here.
        //For demonstration I will just continue with the rest of your code.

        var x = setInterval(function() {
          // Get Date Selected & Convert to ISO
          var n = document.getElementById("myDate").value;
          var d = new Date(n);
          var dISO = d.toISOString();

          // Get Today's Date
          var today = new Date();
          var tS = today.toDateString();
          var tISO = today.toISOString();

          // Calculate Time Left
          var dParse = Date.parse(dISO);
          var tParse = Date.parse(tISO);
          var distance = dParse - tParse;
          // days
          var days = Math.floor(distance / (1000 * 60 * 60 * 24));
          if (days > 0) {
            days = Math.floor(distance / (1000 * 60 * 60 * 24));
          } else {
            days = 0;
          }
          // hours
          var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
          if (hours > 0) {
            hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
          } else {
            hours = 0;
          }
          // minutes
          var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
          if (minutes > 0) {
            minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
          } else {
            minutes = 0;
          }
          // seconds
          var seconds = Math.floor((distance % (1000 * 60)) / 1000);
          if (seconds > 0) {
            seconds = Math.floor((distance % (1000 * 60)) / 1000);
          } else {
            seconds = 0;
          }

          // Print Distance or Expired Message
          if (days > 0 || hours > 0 || days > 0 || seconds > 0) {
            document.getElementById("showDate").innerHTML = days + " days " + hours + " hours " + minutes + " minutes " + seconds + " seconds ";
          } else {
            document.getElementById("showDate").innerHTML = "The time has expired";
          }
        }, 1000);   

      }
    }

store_data.php

<?php
// ONLY Process Form if $_POST is NOT Empty
if ( ! empty( $_POST ) ) {

  // Connect to MySQL
  $mysqli = new mysqli( 'hn', 'un', 'pw', 'db' );

  // Check Our Connection
  if ( $mysqli->connect_error ) {
    die( 'Connect Error: ' . $mysqli->connect_errno . ': ' . $mysqli->connect_error );
  }

  // Insert Our Data
  $sql = "INSERT INTO table ( mydate ) VALUES ( '{$mysqli->real_escape_string($_POST['myDate'])}' )";
  $insert = $mysqli->query($sql);

  // Print Response from MySQL
  if ( $insert ) {
    echo "Success! Row ID: {$mysqli->insert_id}";
  } else {
    die("Error: {$mysqli->errno} : {$mysqli->error}");
  }

  // Close Connection
  $mysqli->close();
}
?>

更新:

如果要從PHP文件發送回多個變量,則可以創建一個關聯數組,並使用json_encode,如下所示:

store_data.php:

$responseData = array(); //create a PHP array
$responseData['status'] = "success"; 
$responseData['myDateSubmitted'] = $_POST['myDate']; //store the date that was submitted into a variable to send back
echo json_encode($responseData); //echo the response data back to the client

displaytimer.js

function ajaxCallback(){
  //this function will be executed once the ajax request is completed
  if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
    //The ajax request was successful.
    //we can now get the response text using xmlhttp.responseText. 
    //parse the response text as JSON because we used json_encode in our PHP file.
    var jsonData = JSON.parse(xmlhttp.responseText);
    console.log(jsonData.myDateSubmitted); //check one of our variables
    //Rest of your code here
  }

}

您應該避免使用POST提交數據,這樣就不會重新加載頁面,因此您不需要吐出任何東西。

使用AJAX將myDate發送到后端,使其在數據庫上持久存在。

簡而言之,您應該在基本的后端REST服務中轉換PHP代碼; 避免在HTML頁面上粘貼PHP代碼並處理發布的數據,這是一種非常古老的處理方式。

后端使用PHP,前端使用JS。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM