php - 如何通过 Ajax 将数据从 HTML 传递到 PHP 文件?
问题描述
我想知道,如何<select>
通过 ajax 将元素从 html 传递到 PHP 文件。
这是我的index.php
:
<p>
<form action = "display.php" method="post" enctype="multipart/form-data">
Select:
<select name="chosenOption" id="chosenOption" style="width:100px"">
<?php
include 'dbConnection.php';
$query = $db->query("SELECT id,name FROM products");
while($row = $query->fetch_assoc())
{
echo'
<option value="'.$row['id'].'">'.$row['name'].'
</option>';
}
?>
</select>
Display : <input type="submit" name="display" value="Display">
</form>
</p>
我display.php
的,我有ajax方法的地方:
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
<script>
function refresh_div() {
var chosenOption= $('#chosenOption').val();
jQuery.ajax({
url: 'products.php',
type:'POST',
data:{chosenOption:chosenOption},
success:function(results) {
jQuery(".result").html(results);
}
});
}
t = setInterval(refresh_div,1000);
</script>
<div class="result"></div>
而且products.php
,我想在哪里传递选定的< select >
元素:
<?php
include 'dbConnection.php';
$chosenOption = $_POST["chosenOption"];
// Display section
$query = $db->query("SELECT cost,description FROM products_info WHERE products_id=$chosenOption);
if($query->num_rows > 0){
while($row = $query->fetch_assoc()){
echo "Actual cost and description: ".$row["cost"]. " ".$row["description"]. ;
}
} else {
echo "No data";
}
?>
我希望选择的选项 fromindex.php
将通过 ajax 传递给 products.php 并显示适当的消息。当前代码不起作用。任何的想法?
解决方案
不能引用$("#chosenOption")
in display.php
,因为页面已经重新加载。您需要使用$_POST['chosenOption']
,因为它是由表单提交的。
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
<script>
function refresh_div() {
var chosenOption= $('#chosenOption').val();
jQuery.ajax({
url: 'products.php',
type:'POST',
data:{chosenOption: <?php echo $_POST['chosenOption']; ?>},
success:function(results) {
jQuery(".result").html(results);
}
});
}
t = setInterval(refresh_div,1000);
</script>
<div class="result"></div>
推荐阅读
- maven - 构建WAR时包不存在
- android - 无法从 com.android.support 库导入。+不同的版本?
- java - Spring-Boot 和 Kafka:如何处理不可用的代理?
- firebase - Firebase Cloud Function -> Google Books API 的 403 状态
- elasticsearch - 在 ElasticSearch 中包含嵌套字段作为结果项
- webpack - 如何将 chunkhash 添加到动态导入的块而不是供应商
- javascript - Google JavaScript API - 需要 JavaScript (Angular) 应用程序作为管理员帐户进行身份验证
- python - 如何访问 __setitem__ 定义 | 语法和例子?
- java - 使用 JRE 9 及更高版本时,我的 Java 应用程序出现放大和扭曲
- amazon-web-services - 使用 AWS.config.credentials 的 Amazon AWS getAttribute()