首页 > 解决方案 > 选择字段未通过 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>

下面是页面/表单的图像

表单的图像,显​​示了两个选择框

这是我从控制台得到的错误

标签: phpjqueryajax

解决方案


这可以帮助你

           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'] 接收数据。


推荐阅读