簡體   English   中英

如何將下拉更改事件鏈接到PHP函數

[英]How to link dropdown change event to PHP function

腳本

下拉菜單中有以下HTML代碼

 <div class="form-group col-sm-2"> <label>Machine</label><br> <select class="combobox form-control col-sm-2" name="machineNumber"> <option>1</option> <option>2</option> </select><br> <label id="machineSer">Machine Serial Number: <?php echo $serialNumberRemarks; ?></label> </div> 

我需要的

當組合框發生變化時,我需要運行以下php函數,該函數運行查詢並獲取數據以根據id為machineSer的標簽顯示相應的項目。 我的php功能如下

<?php
    function labelVal(){
        if(isset($_POST['machineNumber'])){
            $machineName = $_POST['machineNumber'];

            $query = "SELECT machineSerialRemarks FROM machinenames WHERE machineName = '$machineName'";
            $result = mysqli_query($conn, $query);
            $row = mysqli_fetch_array($result);
            $serialNumberRemarks = $row['machineSerialRemarks'];
            return $serialNumberRemarks;
        }
    }
?>

有誰知道該怎么做? 我知道這與Javascript以及可能的Ajax有關。 我瀏覽了一些Ajax,但不了解它是如何工作的。 有沒有不使用Javascript的方法? 如果不可能,如何將這兩個與Javascript和Ajax鏈接起來?

您應該將AJAX用於此任務。 您可以使用jQuery ajax或普通JavaScript ajax。

我已經使用經過測試的香草JavaScript創建了一個完整的工作示例,並且工作正常。

這是我所做的更改:

  1. 我在HTML中的select元素上添加了onchange偵聽器,例如onchange="selectMachineNumber()"
  2. 我創建了一個名為selectMachineNumber的javascript函數,該函數將在每次更改選擇菜單時執行。 在此函數中,我們向一個名為machine_number_processing.php的php文件(包含您的php腳本)發出ajax請求。
  3. 我回顯一個包含serialNumberRemarks變量的json編碼響應。
  4. 然后,我在span標簽(在標簽內)中將serialNumberRemarks插入到您的html中。 span標簽的ID為: machine-serial-number

index.html(或任何HTML頁面名稱)

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script>
//declare a global xmlhttp variable 
var xmlhttp;

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 selectMachineNumber(selectElement){
   //this function will be called when there is a change in the machineNumber select menu
   //check the value selected in the console as follows:
   console.log(selectElement.value);
   var machineNumber = selectElement.value;
   //do ajax request
   xmlhttp = createXHR();
   xmlhttp.onreadystatechange = ajaxCallback; //name of our callback function here
   //Ive called the php file machine_number_processing.php but you can call it whatever you like.
   xmlhttp.open("POST", "machine_number_processing.php" ,true);
   xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
   //send our variables with the request
   xmlhttp.send("machineNumber=" + machineNumber);
}

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
      //we also need to parse this as JSON because we used json_encode on the PHP array we sent back 
      var data = JSON.parse(xmlhttp.responseText);
      console.log(data.machineNumber); 
      console.log(data.serialNumberRemarks);
      //insert the serialNumberRemarks to the span tag with id="machine-serial-number"
      document.getElementById("machine-serial-number").innerText = data.serialNumberRemarks;

   }
}


</script>
</head>
<body>
 <div class="form-group col-sm-2">
  <label>Machine</label><br>
  <select class="combobox form-control col-sm-2" name="machineNumber" id="machineNumber" onchange="selectMachineNumber(this)">
    <option>1</option>
    <option>2</option>
  </select><br>
  <label id="machineSer">Machine Serial Number: <span id="machine-serial-number"></span></label>
</div>
</body>
</html>

machine_number_processing.php

<?php
  if(isset($_POST['machineNumber'])){
    $machineName = $_POST['machineNumber'];

    $query = "SELECT machineSerialRemarks FROM machinenames WHERE machineName = '$machineName'";
    $result = mysqli_query($conn, $query);
    $row = mysqli_fetch_array($result);
    $serialNumberRemarks = $row['machineSerialRemarks'];

    //create a PHP array to store the data we will send back to the client side
    $responseData = array(); 
    //store the machineNumber that was submitted into a variable in order to test the ajax request
    //without performing the SQL query.
    $responseData['machineNumber'] = $_POST['machineNumber']; 

    //store the $serialNumberRemarks variable into our response array
    $responseData['serialNumberRemarks'] = $serialNumberRemarks;
    echo json_encode($responseData); //echo the response data back to the client
  }
?>

注意:正如您所知道的(正如人們在評論中所說的那樣),您需要研究使SQL代碼更安全,但是出於演示目的,我將您的PHP代碼保持原樣。

希望這可以幫助 :)

編輯

如果您只是想測試 ajax請求是否有效(不執行SQL查詢),則將您的php文件更改為以下內容

machine_number_processing.php

<?php
  if(isset($_POST['machineNumber'])){
    $machineName = $_POST['machineNumber'];
    //create a PHP array to store the data we will send back to the client side
    $responseData = array(); 
    //store the machineNumber that was submitted into a variable in order to test the ajax request
    //without performing the SQL query.
    $responseData['machineNumber'] = $_POST['machineNumber']; 

    echo json_encode($responseData); //echo the response data back to the client
  }
?>

然后在ajaxCallback函數中注釋掉這兩行

 console.log(data.serialNumberRemarks);
 document.getElementById("machine-serial-number").innerText = data.serialNumberRemarks;

您可以按照以下步驟檢查在開發人員工具的“網絡”標簽下獲得的響應:

響應

編輯2-使PHP代碼更安全

我想展示一個示例,說明如何在項目中使用PHP數據對象(PDO)擴展。 這是用於訪問PHP中的數據庫的接口。

它具有准備好的語句 ,這有助於使處理更加安全(即有助於防止SQL注入 )。

這是一個如何將其合並到代碼中的工作示例(而不是使用mysqli)

您用於建立連接的文件如下所示:

connect.php

<?php
  //Define our connection variables. (really these credentials should be in a file stored in a private folder on the server but i'll them here for simplicity.)
  //set the character set for more security. (I will use utf8mb4. This is a good idea if you want to store emojis. YOu can just use utf8 though.
  define("HOSTDBNAME", "mysql:host=localhost;dbname=machine_app;charset=utf8mb4");     
  define("USER", "root");    
  define("PASSWORD", ""); 

  //initiate a PDO connection
  $pdoConnection = new PDO(HOSTDBNAME, USER, PASSWORD);
  $pdoConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
  $pdoConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  //set the character set for more security. set it to utf8mb4 so we can store emojis. you can just use utf8 if you like.
  $pdoConnection->exec("SET CHARACTER SET utf8mb4");

?>

創建一個名為phpfunctions.php的文件,以保存一個getSerialNumberRemarks()函數,該函數對數據庫進行查詢以獲取$serialNumberRemarks

phpfunctions.php

<?php
  function getSerialNumberRemarks($machineName, $pdoConnection){
    /*
     * This is a function to access the machinenames table using PDO with prepared statements and named parameters.
     * I have included extra comments (for learning purposes) with appropriate information taken
     * from the documentation here: http://php.net/manual/en/pdo.prepare.php
     */
    $serialNumberRemarks = ""; 
    try{
      //We create our $query with our named (:name) parameter markers 
      //These parameters will be substituted with real values when the statement is executed.
      //Use these parameters to bind any user-input, (N.B do not include the user-input directly in the query).    
      $query ="SELECT machineSerialRemarks FROM machinenames WHERE machineName = :machineName";

      //We now use the PDO::prepare() method on the query.
      //Note: calling PDO::prepare() and PDOStatement::execute() helps to prevent SQL injection attacks by eliminating the need 
      //to manually quote and escape the parameters.    
      $statement = $pdoConnection->prepare($query);

      //We now bind our user-input values.
      //If the user-input is an INT value then use PDO::PARAM_INT, if it is a string then use PDO::PARAM_STR.
      //$machineName will be an INT so bind the value as follows.
      $statement->bindValue(':machineName', $machineName, PDO::PARAM_INT); 
      $statement->execute();
      $statement->setFetchMode(PDO::FETCH_ASSOC);

      while($row = $statement->fetch()){
        $serialNumberRemarks = $row['machineSerialRemarks'];
      }
      return $serialNumberRemarks;
    }catch(PDOException $e){
      throw new Exception($e);
    }   
  }
?>

以下是AJAX請求要發送的文件。 我們需要包括connect.php文件和phpfunctions.php文件。

machine_number_processing.php

<?php
  require("connect.php"); //this file contains our PDO connection configuration
  require("phpfunctions.php"); //this file contains the getSerialNumberRemarks(); function

  if(isset($_POST['machineNumber'])){
    //store $_POST['machineNumber'] into a local variable
    $machineName = $_POST['machineNumber'];

    //checks should be done here to check the input is valid i.e it's a valid length, its valid encoding.
    //You should also filter the input. 
    //This can be done with PHP methods such as trim(), htmlspecialchars(), strip_tags(), stripslashes() 
    //and other methods depending on the type of input.
    //In this demonstration I will perform minimal sanitization of the input. 
    //Note: if its a string use FILTER_SANITIZE_STRING instead
    $machineName = filter_var($machineName, FILTER_SANITIZE_NUMBER_INT);

    //create a PHP array to store the data we will send back to the client side
    $responseData = array(); 

    //call the getSerialNumberRemarks() function and store the serialNumberRemarks returned into our response array
    $responseData['serialNumberRemarks'] = getSerialNumberRemarks($machineName, $pdoConnection);
    echo json_encode($responseData); //echo the response data back to the client
  }
?>

您必須在此處使用jQuery / Ajax。 如果您使用php,則必須先提交表單才能獲取$_POST數據。 這次,我認為您正在尋找元素的event handling 我們試試吧:

在HTML上將代碼更改為此:

 <div class="form-group col-sm-2">
  <label>Machine</label><br>
  <select class="combobox form-control col-sm-2" id="machineNumber" 
       name="machineNumber">
    <option>1</option>
    <option>2</option>
  </select><br>
  <label id="machineSer">Machine Serial Number: 
   </label>
</div>

樣本腳本

     $("#machineNumber").change(function(){
            var id= $("#machineNumber option:selected").text();



           $.ajax({
                url:"call the function to your php",
                method:"POST",
                data:{
                    machinenum:id
                },
                dataType:"json",
                success:function(data){
               $('#machineSer').text("Machine Serial Number: "+data);
         }

      })
    });

您的PHP功能查詢

<?php
function labelVal(){
    if(isset($_POST['machinenum'])){
        $machineName = $_POST['machinenum'];

        $query = "SELECT machineSerialRemarks FROM machinenames WHERE machineName = 
     '$machineName'";
        $result = mysqli_query($conn, $query);
        $row = mysqli_fetch_array($result);

      echo json_encode($row);
    }
  }
?>

希望這可以幫助。

應該看起來像這樣(由於明顯的原因而未經試用)。

請注意,我將name更改為id ,以使其更易於訪問。 我也將您的請求更改為GET,因為a)根據GET合同,它僅從服務器獲取信息,而不存儲任何信息,b)因為它使fetch變得容易一些。 下面的代碼監視<select>的值何時更改,然后將請求發送到PHP后端。 它可以像我的示例一樣是一個單獨的文件,或者您可以測試以查看請求是否具有將其分流到您的函數的machine參數。 當它顯示其值時,我們將返回到JavaScript,並在響應的正文中使用該值,因此我們將使用text將其提取,然后最終將其插入HTML。 請注意,您不能直接使用PHP標記使用它,因為這是在頁面加載之前發生的,並且以后無法在客戶端重新解釋它-我們需要使用普通的標記,並像我展示的那樣更改DOM。

 document.querySelector('#machineNumber').addEventListener('change', evt => { fetch("http://example.com/get_remarks.php?machineNumber=" + evt.target.value) .then(response => response.text()) .then(text => document.querySelector('#machineSer').textContent = text); }) 
 <div class="form-group col-sm-2"> <label>Machine</label><br> <select class="combobox form-control col-sm-2" name="machineNumber" id="machineNumber"> <option>1</option> <option>2</option> </select><br> <label id="machineSer">Machine Serial Number: <span id="machineSer"></span></label> </div> 

暫無
暫無

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

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