You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在insertAdjacentHTML()中追加API返回的foreach循环下拉选项数据?

解决方案

问题核心在于你直接在JS代码里写PHP模板变量——PHP是服务器端运行的,到浏览器端后,JS里的{$valCountry['countryname']}就是纯字符串,不会被解析成实际的国家选项。下面提供两种可行的解决办法:

方法一:把国家列表转为JS数组,动态生成选项

先通过PHP把国家列表转成JSON格式传给前端JS,再用JS循环生成选项:

第一步:在页面头部添加PHP生成的JS变量

<script>
// 将PHP的国家列表转换为JS数组
const countryList = <?php echo json_encode($list_country); ?>;
// 如需默认选中,可同时传入用户信息
const myInfo = <?php echo json_encode($my_info ?? []); ?>;
</script>

第二步:修改JS代码,动态构建选项

$("#rowAdder").click(function () {
  // 创建select元素
  const selectEl = document.createElement('select');
  selectEl.className = 'input-field';
  selectEl.name = 'country';
  selectEl.ariaLabel = '';

  // 添加默认提示选项
  const defaultOption = document.createElement('option');
  defaultOption.value = '';
  defaultOption.textContent = 'Please select Country';
  selectEl.appendChild(defaultOption);

  // 循环生成国家选项
  countryList.forEach(valCountry => {
    const option = document.createElement('option');
    option.value = valCountry.countryname;
    option.textContent = valCountry.countryname;
    // 处理默认选中逻辑(不需要可删除)
    if (myInfo.country1 && myInfo.country1 === valCountry.country1) {
      option.selected = true;
    }
    selectEl.appendChild(option);
  });

  // 构建新行并插入select
  const newRow = document.createElement('div');
  newRow.className = 'row';
  newRow.innerHTML = '<div class="col-md-12" style="margin-bottom: 25px;"> <div class="form-floating mb-3"></div> </div>';
  newRow.querySelector('.form-floating').appendChild(selectEl);

  $('#newinput').append(newRow);
});

方法二:提前渲染隐藏的选项模板,克隆复用

让PHP提前渲染好所有国家选项,存到隐藏容器里,JS需要时直接复用:

第一步:在页面中添加隐藏的选项模板

<!-- 隐藏的模板,存放所有国家选项 -->
<div id="countryOptionsTemplate" style="display: none;">
  {if isset($list_country) && is_array($list_country) && sizeof($list_country) > 0}
    {foreach from=$list_country item=valCountry}
      <option value="{$valCountry['countryname']}">{$valCountry['countryname']}</option>
    {/foreach}
  {/if}
</div>

第二步:修改JS代码,复用模板选项

$("#rowAdder").click(function () {
  // 获取模板里的选项HTML
  const countryOptions = $('#countryOptionsTemplate').html();
  // 构建新行,注意去掉重复的id(id需唯一,不能多次添加相同id)
  const newRowAdd =
    '<div class="row"> <div class="col-md-12" style="margin-bottom: 25px;"> <div class="form-floating mb-3">'+
    '<select class="input-field" name="country" aria-label="">'+
    '<option value="">Please select Country</option>'+
    countryOptions +
    '</select> </div> </div> </div>';

  $('#newinput').append(newRowAdd);
});

内容的提问来源于stack exchange,提问作者felicia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 18:55:35