jquery 无法使用 AJAX 在onchange后初始化select2类

ql3eal8s  于 2023-08-04  发布在  jQuery
关注(0)|答案(1)|浏览(110)

无法启动select 2类后onchange与 AJAX 这是主页面,我不能调用select 2类后选择任何选项,我甚至不知道这是什么所谓的AJAX或只是普通的POST与纯JavaScript

<select name="TDP_Code" class="form-control select2" id="TDP_Code" onchange="cek_TDP();">
   <option value="select" selected>(Select TDP Grp No)</option>
   <option value="1">Content 1</option>
   <option value="2">Content 2</option>
</select>

<div id="result-tdp">
    <div class="row mb-3 ml-4">
         <div class="col-md-2">
             <span>Talent</span>
          </div>
             <span>:</span>
       <div class="col-md-9 ml-5">
         <select class="form-control select3" style="width: 100%;" id="talent">
             <option value="0">(Select Talent)</option>
         </select>
        </div>
    </div>
</div>

<script>
$('.select2').select2({
    theme: 'bootstrap4'
});
function postRequestTDP(strURL) {
      var xmlHttp;
      if (window.XMLHttpRequest) {
        var xmlHttp = new XMLHttpRequest();
      } else if (window.ActiveXObject) {
        var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
      }
      xmlHttp.open("POST", strURL, true);
      xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      xmlHttp.onreadystatechange = function () {
        if (xmlHttp.readyState == 4) {
          updatePageTDP(xmlHttp.responseText);
        }
      };
      xmlHttp.send(strURL);
    }

    function updatePageTDP(str) {
      document.getElementById("result-tdp").innerHTML = str;
    }

    function cek_TDP() {
      id = document.getElementById("TDP_Code");
      var url = "result-select-tdp.php?id=" + id;
      postRequestTDP(url);
      // alert(url);
    }
</script>

字符串
result-select-tdp.php页面,无法在此处调用类select 2

<select name="result_select" class="form-control select2" id="TDP_Code" onchange="cek_TDP();">
   <option value="select" selected>(Select TDP Grp No)</option>
   <option value="result-1">Result 1</option>
   <option value="result-2">Result 2</option>
</select>


如何调用这两个类在不同的网页后张贴与 AJAX

xam8gpfp

xam8gpfp1#

你可以在新的HTML添加到DOM之后,在updatePageTDP()函数中重新初始化Select2:

>  function updatePageTDP(str) {  
> document.getElementById("result-tdp").innerHTML = str;   //
> re-initialize Select2   $('.select2').select2({
>     theme: 'bootstrap4'   }); }

字符串
最好使用 AJAX complete事件来初始化select2:

function postRequestTDP(strURL) {
  var xmlHttp;
  if (window.XMLHttpRequest) {
    var xmlHttp = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlHttp.open("POST", strURL, true);
  xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  xmlHttp.onreadystatechange = function () {
    if (xmlHttp.readyState == 4) {
      updatePageTDP(xmlHttp.responseText);
      // re-initialize Select2
      $('.select2').select2({
        theme: 'bootstrap4'
      });
    }
  };
  xmlHttp.send(strURL);
}

相关问题