Javascript 如何将下拉更改事件链接到PHP函数
场景 我有以下用于下拉菜单的HTML代码Javascript 如何将下拉更改事件链接到PHP函数,javascript,php,html,ajax,mysqli,Javascript,Php,Html,Ajax,Mysqli,场景 我有以下用于下拉菜单的HTML代码 机器 1. 2. 机器序列号: 这里必须使用jQuery/Ajax。如果您使用php,则必须首先提交表单,以获取$\u POST数据。这一次,我认为您正在寻找元素的事件处理。让我们试试: 在HTML上将代码更改为: <div class="form-group col-sm-2"> <label>Machine</label><br> <select class="combobox f
机器
1.
2.
机器序列号:
这里必须使用jQuery/Ajax。如果您使用php,则必须首先提交表单,以获取$\u POST
数据。这一次,我认为您正在寻找元素的事件处理
。让我们试试:
在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>
您的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);
}
}
?>
这里必须使用jQuery/Ajax。如果您使用php,则必须首先提交表单,以获取$\u POST
数据。这一次,我认为您正在寻找元素的事件处理
。让我们试试:
在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>
您的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
更容易一些。下面的代码监视
的值何时更改,然后向PHP后端发送请求。它可以像我的示例中那样是一个单独的文件,或者您可以测试请求是否具有machine
参数以将其分流到您的函数。当它打印它的值时,我们回到JavaScript,在响应的主体中包含该值,因此我们将使用text
提取它,最后将其插入HTML。请注意,不能直接使用PHP标记,因为这是在加载页面之前发生的,以后在客户端无法重新解释它-我们需要使用普通标记,并像我所展示的那样更改DOM
document.querySelector('#machineNumber').addEventListener('change',evt=>{
取回(“http://example.com/get_remarks.php?machineNumber=“+evt.target.value)
.then(response=>response.text())
.then(text=>document.querySelector(“#machineSer”).textContent=text);
})
机器
1.
2.
机器序列号:
应该是这样的(由于明显的原因未经测试)
请注意,我将name
更改为id
,以使其更易于访问。我还将您的请求更改为GET,因为a)它只从服务器获取信息,而不按照GET合同存储任何内容;b)因为它使fetch
更容易一些。下面的代码监视
的值何时更改,然后向PHP后端发送请求。它可以像我的示例中那样是一个单独的文件,或者您可以测试请求是否具有machine
参数以将其分流到您的函数。当它打印它的值时,我们回到JavaScript,在响应的主体中包含该值,因此我们将使用text
提取它,最后将其插入HTML。请注意,不能直接使用PHP标记,因为这是在加载页面之前发生的,以后在客户端无法重新解释它-我们需要使用普通标记,并像我所展示的那样更改DOM
document.querySelector('#machineNumber').addEventListener('change',evt=>{
取回(“http://example.com/get_remarks.php?machineNumber=“+evt.target.value)
.then(response=>response.text())
.then(text=>document.querySelector(“#machineSer”).textContent=text);
})
机器
1.
2.
机器序列号:
此任务应使用AJAX。您可以使用jQuery ajax或vanilla JavaScript ajax
我已经用香草JavaScript创建了一个完整的工作示例,我已经测试过了,效果很好
以下是我所做的更改:
我在HTML中的select元素中添加了一个onchange
侦听器,例如onchange=“selectMachineNumber()”
我创建了一个名为selectMachineNumber
的javascript函数,每次更改选择菜单时都会执行该函数。在这个函数中,我们向一个名为machine\u number\u processing.php(包含您的php脚本)的php文件发出ajax请求李>
我回显包含serialnumbermarks
变量的json编码响应李>
然后,我将serialnumbermarks
插入到span标记(在标签内)中的html中。span标签的id为:机器序列号
index.html(或html页面的任何名称)
您可以在开发人员工具中的“网络”选项卡下检查得到的响应,如下所示:
编辑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");
?>
<?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);
}
}
?>
<?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
}
?>
下面是AJAX请求将要访问的文件。我们需要包括connect.php文件和phpfunctions.php文件
machine\u number\u processing.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");
?>
<?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);
}
}
?>
<?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
}
?>
此任务应使用AJAX。您可以使用jQuery ajax或vanilla JavaScript ajax
我已经用香草JavaScript创建了一个完整的工作示例,我已经测试过了,效果很好
以下是我所做的更改:
我在HTML中的select元素中添加了一个onchange
侦听器,例如onchange=“selectMachineNumber()”
我创建了一个名为selectMachineNu的javascript函数