php - 选择字段未通过 Ajax 填充
问题描述
我想实现这个功能。当想要发布广告的用户选择一个类别时,.change()
JQUERY 方法会触发一个 AJAX 请求,该请求将从 SUB-CATEGORIES 表中请求属于所选 CATEGORY 的子类别,并将结果附加到下一个 SELECT FIELD。但到目前为止,它没有得到结果。
这是我的代码片段。
subcat.php
<?php
include 'includes/config.php';
if (isset($_POST['category'])) {
$cat = mysqli_real_escape_string($link, $_GET['category']);
//select category id from categories table where Title = $cat
$catIdSel = "SELECT cat_id FROM categories WHERE catTitle = '$cat'";
$catIdSelKwary = mysqli_query($link, $catIdSel);
$catIdSelCount = mysqli_nums_row($catIdSelKwary);
if ($catIdSelCount == 1) {
$catIdRow = mysqli_fetch_array($catIdSelKwary);
$cat_id = $catIdRow['cat_id'];
}
//select from sub-categories table all the sub-categories that have the same cat_id with the returned cat_id from the dategories table
$subCatSel = "SELECT Title FROM sub_categories WHERE cat_id = '$cat_id'";
$subCatSelKwary = mysqli_query($link, $subCatSel);
$subCatSelCount = mysqli_nums_row($subCatSelKwary);
if ($catIdSelCount > 0) {
while ($subCatRow = mysqli_fetch_array($subCatSelKwary)) {
echo '<option value="'.$subCatRow['Title'].'">' .$subCatRow['Title']. '</option>';
}
}else{
echo "No Sub Category for this Category yet";
}
}
postad.php - 我的 Jquery 在哪里
<script type="text/javascript">
$(document).ready(function () {
$('#category').change(function () {
//display loading option
$('#sub-category').html('<option value="">Fetching Sub Categories...</option>');
//collect select value
var category = $('#category').val();
$.ajax({
URL: 'sel_subcat.php?cat' + category,
method: 'POST',
data: category,
success: function (data) {
//append the data to the select field
$('#sub-category').html(data);
},
error: function () {
console.log(xhr.status + " " + thrownError);
}
});
});
});
</script>
下面是页面/表单的图像
解决方案
这可以帮助你
var category = $('#category').val();
$.ajax({
URL: 'sel_subcat.php',
method: 'POST',
data: {category:category},
success:function(data){
//append the data to the select field
$('#sub-category').html(data);
},
error:function () {
console.log(xhr.status + " " + thrownError);
}
});
并使用 $_POST['category'] 接收数据。
推荐阅读
- javascript - 如何使用 SS 2.0 将计划脚本中的用户名传递给 PDF 模板?
- python - Python Pandas 根据 If/Else 获取值
- php - 路由中的 $1 返回 404 错误,而不是将 url 段传递给控制器方法
- javascript - 为两个字符定义一个正则表达式,然后是两个数字
- angular - 如何在其他地方使用 subscribe() 的数据?
- android - 如何使用 Firebase 将毕加索图像添加到 ArrayList
- xslt - 创建 html 表时避免重复
- nativescript - 当应用程序在 android 平台的前台时,Firebase 推送通知不显示
- php - Symfony:在 FormType 表单中为 EntityType 使用不同的字段
- selenium - 在命令提示符下运行 selenium 测试套件时有等待/超时