如何在PHP Ajax响应文本动态创建里面选择标记的选择吗?标记、文本、里面、动态

2023-09-10 20:34:23 作者:初夏あ蔷薇花

我有HTML code这样的下拉列表。

I have html code like this for drop down list.

<select id="province" onchange="get_twn()">
<option value="western">Western</option>
<option value="southern">Southern</option>
</select>

<select id="towns" name="towns">
</select>

这是我的ajax $ C $下 get_twn

function get_twn(){

    var e = document.getElementById('province');    
    var val = e.options[e.selectedIndex].value;
    var xmlhttp;
    alert('i came');
        if (window.XMLHttpRequest)
          {
          xmlhttp=new XMLHttpRequest();
          }
        else
          {
          xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
          }

        xmlhttp.onreadystatechange=function(){          
          if (xmlhttp.readyState==4 && xmlhttp.status==200)
            {
                //window.location.assign("login.php");
                var val = xmlhttp.responseText; 
                var selectList = document.getElementById('towns');          
                var option = document.createElement('option');
                option.value = val;
                option.text = val;
                selectList.appendChild(option);

            }
      }
    xmlhttp.open("POST","test.php?a="+val,true);
    xmlhttp.send();
}

这是PHP code 的test.php

This is the php code test.php.

if(isset($_REQUEST["a"])){

        $result = $dba->get_twn($_REQUEST["a"]);
        while($row = mysql_fetch_array($result))
        {
            $val = $row['name'];
            echo $val;          
        }
}

这code运作良好,但有一点差错。当此code执行会造成选项标记,但所有的值彼此结合​​,并创建只有一个tag.Like此选项。 然而,它应该会出现类似这样的。

This code working well but there is little mistake. When this code execute it will create option tag but all values combine with each other and create only one option tag.Like this. However it should appear like this.

推荐答案

首先,你的PHP改成这样:

First, change your PHP to this:

test.php的:

if(isset($_REQUEST["a"])){

        $result = $dba->get_twn($_REQUEST["a"]);

        $towns = array();

        while($row = mysql_fetch_array($result))
        {
            $towns[] = $row['name'];    
        }

        echo json_encode($towns);
}

,并在你的函数get_twn改变这样的:

    xmlhttp.onreadystatechange=function(){          
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            //window.location.assign("login.php");
            var selectList = document.getElementById('towns');    

            var jsonData = JSON.parse(val);

            for (var i in jsonData) {
              var option = document.createElement('option');
              option.value = jsonData[i];
              option.text = jsonData[i];
              selectList.appendChild(option);
            }

        }
    }
 
精彩推荐
图片推荐