AJAX没有显示数据

时间:2017-07-15 12:11:35

标签: javascript php jquery ajax

我有两个选择,第二个是隐藏,如果第一个选择已经更改,应该显示它,我通过on('change', function(){ ...检查它并且它到目前为止工作。我已经检查过,并在第一个选择框更改时显示了console.log。

这里的主要问题是当我从第一个选择框中选择一个选项时,它应该使用 AJAX 发送一些请求。我已向 fetch_sections.php 发送了一些请求,

这是我的更新脚本:

<script>
    $(document).ready(function() {
        $('select').material_select();
        $('#school-list').on('change', function() {
            $.ajax({
                url: 'fetch_sections.php',
                type: 'post',
                dataType: 'html',
                data: {parent: $(this).val() },
                success: function(data)
                {
                    $('#section-list').empty();
                    $('#section-list').html(data);
                    console.log(data);
                }
            });
            $('#hideThis').show("slow");
        });
    });
</script>

这是我的 fetch_sections.php (工作,使用 PostMan检查):

<?php
    require '../assets/php/init.php';

    if ($_POST)
    {
        $schoolID   = Essentials::sanitize($_POST['parent']);

        $fetchSQL   = "SELECT `sectionid`, `name` FROM `sections` WHERE schoolid = ?";
        $fetch      = $conn->prepare($fetchSQL);
        $fetch->execute([$schoolID]);
        $fetchRes   = $fetch->fetchAll(PDO::FETCH_ASSOC);
        if(!$fetchRes) {
            echo '
                <option value="" disabled selected>Unfortunately, there is no section here.</option>
            ';
        } else {
            foreach ($fetchRes as $section)
            {
                echo '
                    <option value="'.$section['sectionid'].'"">'.$section['name'].'</option>
                ';
            }
        }
    }

这是我的选择HTML 也已更新

            <div class="row margin">
              <div class="input-field col s12">
                <select id="school-list" name="school-list">
                  <option value="" disabled selected>Choose your school</option>
                    ...
                </select>
                <label>School</label>
              </div>
            </div>
                <div class="row margin" id="hideThis" style="display:none">
                  <div class="input-field col s12">
                    <select id="section-list" name="section-list">
                      <option value="" disabled selected>Choose your section</option>
                    </select>
                    <label>Section</label>
                  </div>
                </div>

更新 [由 ccKep 建议]:

我现在可以通过console.log(data)查看我想要的数据,它输出的内容是:

<option value="9-1">9-A...</option>,现在我想将它添加到我的主要选择列表中,但它不允许我这样做。

输出应为:

                <select id="section-list" name="section-list">
                  <option value="" disabled selected>Choose your section</option>
                  <option value="9-1">9-A...</option>
                </select>

0 个答案:

没有答案