【问题标题】:how to enter dynamic data to a javascript function after page load页面加载后如何将动态数据输入到javascript函数
【发布时间】:2023-01-08 20:47:11
【问题描述】:

我有一个选择框,哪些选项来自数据库,具体取决于使用 ajax 的另一个选定选项

$(document).ready(function(){
    $("select.entity").change(function(){
        var selectedEntity = $(".entity option:selected").val();
        $.ajax({
            type: "POST",
            url: "entityName.php",
            data: { entity : selectedEntity } 
        }).done(function(data){
            $("#entityName").html(data);
        });
    });
});

// This is the select box where options are dynamic.

<label>Select Entity Name:</label>
<select id="entityName" name="entityName" class="select_box" required>
     <option value="" disabled selected>Select Entity Type First</option>
</select>

这工作正常,但现在我想要一个用于选项的搜索框。我正在使用此功能进行搜索。

var select_box_element = document.querySelector('.select_box');
dselect(select_box_element, {
        search: true
       });

由于选项是动态的并在页面加载后加载,因此此功能不起作用。

我需要根据选择将动态选项推送到 dselect 函数中。

【问题讨论】:

  • 什么是选择?
  • 添加高级功能(如实时搜索、动态创建、字段验证)的 JavaScript 库
  • 请点击edit 然后点击[&lt;&gt;] 并创建一个minimal reproducible example - 你可以制作一个示例数据对象,因为 ajax 工作正常吗?
  • 我似乎找不到 dselect cdn。是这个吗? dselect.vercel.app
  • @mplungjan 是的。

标签: javascript jquery ajax


【解决方案1】:
}).done(function(data){
  $("#entityName").html(data);
  dselect($("#entityName")[0], { search: true });
});

示例 - 我认为您需要添加一些 CSS

const $select_box_element = $('#entityName');
const $entity = $('#entityType');
$("select.entity").change(function(){
  if (this.value === "one") {
    $select_box_element.html(`<option value="one">One</option><option value="oneone">OneOne</option>`)
    dselect($select_box_element[0], { search: true });
  }
  else {
    $select_box_element.html(`<option value="two">Two</option><option value="twotwo">TwoTwo</option>`)
    dselect($select_box_element[0], { search: true });
  }
});

dselect($entity[0], { search: true });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/@jarstone/dselect/dist/css/dselect.css">
<script src="https://unpkg.com/@jarstone/dselect/dist/js/dselect.js"></script>
<label>Select Entity Type:</label>
<select id="entityType" name="entityType" class="entity" required>
  <option value="" disabled selected>Select Entity Type</option>
  <option value="one">One</option>
  <option value="two">Two</option>
</select>
<label>Select Entity Name:</label>
<select id="entityName" name="entityName" class="select_box" required>
  <option value="" disabled selected>Select Entity Type First</option>
  <option value="one">One</option>
  <option value="one">One</option>
</select>

【讨论】:

    【解决方案2】:

    这样的事情可能对你有用。我为 dselect 库使用了 CSS 和 JS,如 the official GitHub repo 所示。在示例中,还包括 Bootstrap 5 文件,因为 dSelect 似乎依赖于 Bootstrap 5 文件。

    使用的 API 来自免费的Pokemon API

    关于如何处理 AJAX 的轻微重写的一些注意事项:

    • 无需调用 AJAX,如果第一个 select 元素内没有任何内容,并且我们恢复为默认的 #entityType 值。我们只需要清除#entityName之前的内容即可。这就是 ifchange 事件处理程序中所做的
    • AJAX 调用包含预定义的 dataType 属性。这样做是因为我事先知道我的示例中的 response(Pokemon API 的响应)将采用 JSON 格式。如果您控制后端/entityName.php 工作并输出其结果的方式,您也可以在特定情况下执行此操作。如果你没有那种控制,你可能想省略这个 AJAX 配置参数,并以不同的方式处理结果
    • 该示例使用单独的successerror 处理程序,而不是使用$.ajax({...}).done(...)。这只是一个偏好选择。 successdone的使用区别,请参考this SO answer。在您的特定情况下,.done(...) 也可以正常工作,如果收到的 data 与您期望的相匹配,则进行额外测试,如下所示:
    $.ajax({
    // your ajax setup
    }).done(function(data){
      if(data) {
          $("#entityName").html(data);
      } else {
          $("#entityName").html('<option value="" disabled selected>Select Entity Type First</option>');
      }
    
      dselect($("#entityName")[0], { search: true });
    });
    
    • 该示例还使用config,如官方 GitHub 存储库所示。同样,如果您对初始化 dselect 的方式感到满意,则可以跳过配置

    $(document).ready(function(){
        const config = {
            search: false, // Toggle search feature. Default: false
            creatable: false, // Creatable selection. Default: false
            clearable: false, // Clearable selection. Default: false
            maxHeight: '360px', // Max height for showing scrollbar. Default: 360px
            size: '', // Can be "sm" or "lg". Default ''
        }
        dselect($("#entityName")[0], config);
    
        $("#entityType").change(function(){
            let entityType = $(this).val();
            if(!entityType) {
              $("#entityName").html('<option value="" disabled selected>Select Entity Type First</option>');
              dselect($("#entityName")[0], config);
              return false;
            }
            
            $.ajax({
                type: "GET",
                url: "https://pokeapi.co/api/v2/type/" + entityType,
                dataType: "json",
                success: function(data) {
                  let pokemon = data.pokemon;
                  let pokeList = '<option value="" selected>Please choose your Pokemon</option>';
                  console.log(pokemon[0].pokemon.name);
                  for(var i = 0; i < pokemon.length; i++) {
                    let pokeName = pokemon[i].pokemon.name;
                    let pokeUrl = pokemon[i].pokemon.url;
    
                    pokeList += '<option value="' + pokeUrl + '">' + pokeName + '</option>';
                  }
                  
                  $("#entityName").html(pokeList);
                  dselect($("#entityName")[0], config);
                },
                error: function(desc, err) {
                    alert("Error: " + JSON.stringify(desc) + ", " + JSON.stringify(err));
                }
            });
        });
    });
    label {
      margin-left: 15px;
    }
    
    #entityType {
      margin: 15px 0 15px 15px;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <link rel="stylesheet" href="https://unpkg.com/@jarstone/dselect/dist/css/dselect.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>
    <script src="https://unpkg.com/@jarstone/dselect/dist/js/dselect.js"></script>
    <label for="entityType">Select Entity Type:</label>
    <select id="entityType" name="entityType" class="select_box" required>
         <option value="">Choose</option>
         <option value="water">Water</option>
         <option value="fire">Fire</option>
         <option value="ground">Ground</option>
         <option value="electric">Electric</option>
         <option value="flying">Flying</option>
    </select>
    <select id="entityName" name="entityName" class="select_box" required>
         <option value="" disabled selected>Select Entity Type First</option>
    </select>
    <div id="list"></div>

    【讨论】:

      猜你喜欢
      • 2014-03-21
      • 1970-01-01
      • 2020-06-14
      • 1970-01-01
      • 2016-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-22
      相关资源
      最近更新 更多