使用 PHP 渲染条件 HTML 元素
Rendering conditional HTML elements with PHP
我正在尝试学习 PHP 来解决评估挑战,我必须在其中构建产品列表并添加产品页面。
在这里和那里阅读,观看一些教程,到目前为止我能够开发这段代码:
Index.php:
<?php include("db.php"); ?>
<?php include("includes/header.php"); ?>
<div class="container p-4">
<div class="row">
<div class="col-md-4">
<div class="card card-body">
<!--INPUT FORM
it will contains the form to add new product to the database:
Fields: SKU / NAME / PRICE / PROD_TYPE / DVD / BOOK / FUR_H / FUR_W / FUR_L -->
<form action="index.php" method="POST">
<div class="form-group">
<input type="text" name="sku" class="form-control" placeholder="Enter SKU Code">
<hr/>
<input type="text" name="name" class="form-control" placeholder="Enter Product Name">
<hr/>
<input type="text" name="price" class="form-control" placeholder="Enter Price">
<hr/>
<label>Product Type</label>
<select id="prod_type" name="prod_type" class="form-control" >
<option value="">Select Product Type</option>
<option value="DVD">DVD</option>
<option value="BOOK">BOOK</option>
<option value="FUR">FURNITURE</option>
</select>
<!-- <hr/> -->
<!--if the select(prod_type) option = DVD, then show the following fields:
Fields: DVD_SIZE
if the select(prod_type) option = BOOK, then show the following fields:
Fields: BOOK_WEIGHT
if the select(prod_type) option = FUR, then show the following fields:
Fields: FUR_H / FUR_W / FUR_L -->
<hr/>
<?php if(isset($_POST['prod_type']) && $_POST['prod_type'] == 'DVD'){ ?>
<input type="text" name="dvd_size" class="form-control" placeholder="Enter DVD Size">
<?php } else if(isset($_POST['prod_type']) && $_POST['prod_type'] == 'BOOK'){ ?>
<input type="text" name="book_weight" class="form-control" placeholder="Enter Book Weight">
<?php } else if(isset($_POST['prod_type']) && $_POST['prod_type'] == 'FUR'){ ?>
<hr/>
<input type="text" name="fur_h" class="form-control" placeholder="Enter Furniture Height">
<hr/>
<input type="text" name="fur_w" class="form-control" placeholder="Enter Furniture Width">
<hr/>
<input type="text" name="fur_l" class="form-control" placeholder="Enter Furniture Length">
<?php } ?>
<!-- <hr/> -->
</div>
<hr/>
<input type="submit" name="add_product" class="btn btn-success w-100" value="Add Product">
</form>
</div>
</div>
<div class="col-md-8">
</div>
</div>
</div>
<?php include("includes/footer.php"); ?>
事实是,DVD 尺寸、书籍重量和家具尺寸(H、W 和 L)的输入应根据#prod_type 上的用户selection 进行渲染。目前,这些输入在用户选择 select 选项后显示,然后点击添加产品按钮(与我按下的 POST 方法相关,是我得到的最接近的方法)
PHP 完全在服务器上运行。如果您希望当您的用户与您的网页交互时浏览器中发生一些事情(而不执行到服务器的往返),Javascript 是您的朋友。
在这种情况下,我会给每个输入一个 data
属性来说明它们与哪种产品类型相关。然后您可以编写一个 Javascript 函数来处理对 prod_type
字段和 show/hide 正确字段的更改。
例如:
function toggleFields() {
var productType = document.getElementById('prod_type').value;
var fields = document.querySelectorAll('[data-if-prod-type]');
fields.forEach(function (field) {
if (field.dataset.ifProdType === productType) {
field.style.display = '';
} else {
field.style.display = 'none';
}
});
}
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('prod_type').addEventListener('change', toggleFields);
// Run the toggle function when the DOM is ready loading,
// so that fields that are not relevant to #prod_type's
// initial value are hidden.
toggleFields();
});
<select id="prod_type" name="prod_type" class="form-control">
<option value="">Select Product Type</option>
<option value="DVD">DVD</option>
<option value="BOOK">BOOK</option>
<option value="FUR">FURNITURE</option>
</select>
<input type="text" name="dvd_size" class="form-control" placeholder="Enter DVD Size" data-if-prod-type="DVD">
<input type="text" name="book_weight" class="form-control" placeholder="Enter Book Weight" data-if-prod-type="BOOK">
<div data-if-prod-type="FUR">
<hr/>
<input type="text" name="fur_h" class="form-control" placeholder="Enter Furniture Height">
<hr/>
<input type="text" name="fur_w" class="form-control" placeholder="Enter Furniture Width">
<hr/>
<input type="text" name="fur_l" class="form-control" placeholder="Enter Furniture Length">
</div>
你可以试试AJAX。它易于使用,而且您会喜欢它的功能。使用 AJAX 可以轻松完成您想要在页面中显示的内容。如果您对 Javascript 和 jQuery 略知一二,您一定会爱上它。
W3School 可以为您详细讲解 - AJAX Introduction
在您的代码中使用 AJAX 的示例,
index.php:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Index Page</title>
</head>
<body>
<?php
if(isset($_POST['prod_type'])){
print_r($_POST); die;
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<select name="prod_type" onchange="getProdOptions(this.value)">
<option value="">Select Product Type</option>
<option value="DVD">DVD</option>
<option value="BOOK">BOOK</option>
<option value="FUR">FURNITURE</option>
</select>
<div id="option_area"></div>
<input type="submit" name="add">
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> // CDN link of jQuery, you can get from - https://cdnjs.com/libraries/jquery
<script type="text/javascript">
function getProdOptions(val) {
val = val.trim();
if(val !== '') {
$.ajax({
url: "/ajax_request.php", // url is the destination to receive the request
data: {
prod_type: val
}, // data is the key and the value you are sending
type: "POST", // method is GET, POST, etc..
success: function( response ) {
response = JSON.parse( response );
if( response.status ){
document.getElementById( 'option_area' ).innerHTML = response.data; // Pure JS Syntax
}else{
alert('No data for the selected prod type.');
}
}
});
}else{
$("#option_area").html(""); // jQuery Syntax
}
}
</script>
ajax_request.php:
<?php
if( isset( $_POST['prod_type'] ) && !empty( $_POST['prod_type'] ) ) {
$response = ['status' => true];
// any condition to check and the condition not met thenn send the status as false
$html = '<input type="text" name="dvd_size" class="form-control" placeholder="Enter DVD Size">';
$html .= '<input type="text" name="book_weight" class="form-control" placeholder="Enter Book Weight">'; // `.=` will concatenate the strings
$response['data'] = $html;
echo json_encode( $response );
}
?>
我正在尝试学习 PHP 来解决评估挑战,我必须在其中构建产品列表并添加产品页面。 在这里和那里阅读,观看一些教程,到目前为止我能够开发这段代码:
Index.php:
<?php include("db.php"); ?>
<?php include("includes/header.php"); ?>
<div class="container p-4">
<div class="row">
<div class="col-md-4">
<div class="card card-body">
<!--INPUT FORM
it will contains the form to add new product to the database:
Fields: SKU / NAME / PRICE / PROD_TYPE / DVD / BOOK / FUR_H / FUR_W / FUR_L -->
<form action="index.php" method="POST">
<div class="form-group">
<input type="text" name="sku" class="form-control" placeholder="Enter SKU Code">
<hr/>
<input type="text" name="name" class="form-control" placeholder="Enter Product Name">
<hr/>
<input type="text" name="price" class="form-control" placeholder="Enter Price">
<hr/>
<label>Product Type</label>
<select id="prod_type" name="prod_type" class="form-control" >
<option value="">Select Product Type</option>
<option value="DVD">DVD</option>
<option value="BOOK">BOOK</option>
<option value="FUR">FURNITURE</option>
</select>
<!-- <hr/> -->
<!--if the select(prod_type) option = DVD, then show the following fields:
Fields: DVD_SIZE
if the select(prod_type) option = BOOK, then show the following fields:
Fields: BOOK_WEIGHT
if the select(prod_type) option = FUR, then show the following fields:
Fields: FUR_H / FUR_W / FUR_L -->
<hr/>
<?php if(isset($_POST['prod_type']) && $_POST['prod_type'] == 'DVD'){ ?>
<input type="text" name="dvd_size" class="form-control" placeholder="Enter DVD Size">
<?php } else if(isset($_POST['prod_type']) && $_POST['prod_type'] == 'BOOK'){ ?>
<input type="text" name="book_weight" class="form-control" placeholder="Enter Book Weight">
<?php } else if(isset($_POST['prod_type']) && $_POST['prod_type'] == 'FUR'){ ?>
<hr/>
<input type="text" name="fur_h" class="form-control" placeholder="Enter Furniture Height">
<hr/>
<input type="text" name="fur_w" class="form-control" placeholder="Enter Furniture Width">
<hr/>
<input type="text" name="fur_l" class="form-control" placeholder="Enter Furniture Length">
<?php } ?>
<!-- <hr/> -->
</div>
<hr/>
<input type="submit" name="add_product" class="btn btn-success w-100" value="Add Product">
</form>
</div>
</div>
<div class="col-md-8">
</div>
</div>
</div>
<?php include("includes/footer.php"); ?>
事实是,DVD 尺寸、书籍重量和家具尺寸(H、W 和 L)的输入应根据#prod_type 上的用户selection 进行渲染。目前,这些输入在用户选择 select 选项后显示,然后点击添加产品按钮(与我按下的 POST 方法相关,是我得到的最接近的方法)
PHP 完全在服务器上运行。如果您希望当您的用户与您的网页交互时浏览器中发生一些事情(而不执行到服务器的往返),Javascript 是您的朋友。
在这种情况下,我会给每个输入一个 data
属性来说明它们与哪种产品类型相关。然后您可以编写一个 Javascript 函数来处理对 prod_type
字段和 show/hide 正确字段的更改。
例如:
function toggleFields() {
var productType = document.getElementById('prod_type').value;
var fields = document.querySelectorAll('[data-if-prod-type]');
fields.forEach(function (field) {
if (field.dataset.ifProdType === productType) {
field.style.display = '';
} else {
field.style.display = 'none';
}
});
}
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('prod_type').addEventListener('change', toggleFields);
// Run the toggle function when the DOM is ready loading,
// so that fields that are not relevant to #prod_type's
// initial value are hidden.
toggleFields();
});
<select id="prod_type" name="prod_type" class="form-control">
<option value="">Select Product Type</option>
<option value="DVD">DVD</option>
<option value="BOOK">BOOK</option>
<option value="FUR">FURNITURE</option>
</select>
<input type="text" name="dvd_size" class="form-control" placeholder="Enter DVD Size" data-if-prod-type="DVD">
<input type="text" name="book_weight" class="form-control" placeholder="Enter Book Weight" data-if-prod-type="BOOK">
<div data-if-prod-type="FUR">
<hr/>
<input type="text" name="fur_h" class="form-control" placeholder="Enter Furniture Height">
<hr/>
<input type="text" name="fur_w" class="form-control" placeholder="Enter Furniture Width">
<hr/>
<input type="text" name="fur_l" class="form-control" placeholder="Enter Furniture Length">
</div>
你可以试试AJAX。它易于使用,而且您会喜欢它的功能。使用 AJAX 可以轻松完成您想要在页面中显示的内容。如果您对 Javascript 和 jQuery 略知一二,您一定会爱上它。 W3School 可以为您详细讲解 - AJAX Introduction
在您的代码中使用 AJAX 的示例,
index.php:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Index Page</title>
</head>
<body>
<?php
if(isset($_POST['prod_type'])){
print_r($_POST); die;
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<select name="prod_type" onchange="getProdOptions(this.value)">
<option value="">Select Product Type</option>
<option value="DVD">DVD</option>
<option value="BOOK">BOOK</option>
<option value="FUR">FURNITURE</option>
</select>
<div id="option_area"></div>
<input type="submit" name="add">
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> // CDN link of jQuery, you can get from - https://cdnjs.com/libraries/jquery
<script type="text/javascript">
function getProdOptions(val) {
val = val.trim();
if(val !== '') {
$.ajax({
url: "/ajax_request.php", // url is the destination to receive the request
data: {
prod_type: val
}, // data is the key and the value you are sending
type: "POST", // method is GET, POST, etc..
success: function( response ) {
response = JSON.parse( response );
if( response.status ){
document.getElementById( 'option_area' ).innerHTML = response.data; // Pure JS Syntax
}else{
alert('No data for the selected prod type.');
}
}
});
}else{
$("#option_area").html(""); // jQuery Syntax
}
}
</script>
ajax_request.php:
<?php
if( isset( $_POST['prod_type'] ) && !empty( $_POST['prod_type'] ) ) {
$response = ['status' => true];
// any condition to check and the condition not met thenn send the status as false
$html = '<input type="text" name="dvd_size" class="form-control" placeholder="Enter DVD Size">';
$html .= '<input type="text" name="book_weight" class="form-control" placeholder="Enter Book Weight">'; // `.=` will concatenate the strings
$response['data'] = $html;
echo json_encode( $response );
}
?>