dongping1689 2015-03-03 07:47
浏览 50

AJAX PHP:使用AJAX的动态下拉列表

Today, I went to code a form with Dynamic dropwdown list in it.

Mission : I want to make dynamic dropdown list when User choose Category, then the store with that category will appear.

It is the form :

<select name="category" class="form-control" id="category" onchange="ajaxStore(this.value)">
   <option value="-1"> - Choose Category -</option>
      <?php
           $StoreCategoriesAPIAccessor = new StoreCategoriesAPIService(GuzzleClient::getClient());
           $stores = $StoreCategoriesAPIAccessor->getStoreCategories();
           foreach ($stores as $store):      
      ?>
   <option value="<?php echo $store->getStoreCategoryId(); ?>"><?php echo $store->getCategory(); ?></option>
      <?php endforeach; ?>
</select>

<label for="inputName" class="control-label">Store Name</label>
  <select name="store" class="form-control" id="store">
     <option value="-1"> - Choose Store -</option>
  </select>

This is the AJAX :

<!-- linking drop down AJAX -->
    <script type="text/javascript">
      var ajaxku=buatajax();
      function ajaxStore(id){
        var url="objects/StoreAPIService.php?category="+id+"&sid="+Math.random();
        ajaxku.onreadystatechange=stateChanged;
        ajaxku.open("GET",url,true);
        ajaxku.send(null);
      }

      function buatajax(){
        if (window.XMLHttpRequest){
          return new XMLHttpRequest();
        }
        if (window.ActiveXObject){
          return new ActiveXObject("Microsoft.XMLHTTP");
        }
        return null;
      }

      function stateChanged(){
        var data;
        if (ajaxku.readyState==4){
          data=ajaxku.responseText;
          if(data.length>=0){
            document.getElementById("store").innerHTML = data
          }else{
            document.getElementById("store").value = "<option selected>- Choose Store -</option>";
          }
        }
      }
    </script>

And this the code of StoreAPIService.php :

session_start();
        $stores = array();

        $store_category_id = $_GET['category'];

        try 
        {
            //$client = new GuzzleClient();
            $response = $this->client->get('admin/store/bycat/rev/'.$store_category_id,
                ['headers' => ['Authorization' => $_SESSION['login']['apiKey']]
            ]);

            $statusCode = $response->getStatusCode();
            // Check that the request is successful.
            if ($statusCode == 200) 
            {
                $error = $response->json();
                echo"<option value=''>- Choose Store -</option>";

                foreach ($error['stores'] as $store) 
                {
                    $mainStore = new StoreSummary();
                    echo "<option value='{$mainStore->setStoreId($store['store_id'])};'>{$mainStore->setStoreName($store['store_name'])};</option>";
                    array_push($stores, $mainStore);
                }
            }
        }

I got no error, but the Store with 'Category' that I Choose is not appearing.

Could anyone please check if I went wrong.

thanks for your helps.

  • 写回答

1条回答 默认 最新

  • dongtan6543 2015-03-03 08:05
    关注

    You were trying to change options of a dropdown menu. i did this by changing dropdown menu itself.
    I created a div with id="store" in the html form and changing the innerHTML of div using ajax

    html form

        <select name="category" class="form-control" id="category" onchange="ajaxStore(this.value)">
           <option value="-1"> - Choose Category -</option>
              <?php
                   $StoreCategoriesAPIAccessor = new StoreCategoriesAPIService(GuzzleClient::getClient());
                   $stores = $StoreCategoriesAPIAccessor->getStoreCategories();
                   foreach ($stores as $store):      
              ?>
           <option value="<?php echo $store->getStoreCategoryId(); ?>"><?php echo $store->getCategory(); ?></option>
              <?php endforeach; ?>
        </select><label for="inputName" class="control-label">Store Name</label>
          <div id="store"><select name="store" class="form-control">
         <option value="-1"> - Choose Store -</option>
      </select>
    </div> <!--end of store -->
    

    ajax code

    <!-- linking drop down AJAX -->
        <script type="text/javascript">
          var ajaxku=buatajax();
          function ajaxStore(id){
            var url="objects/StoreAPIService.php?category="+id+"&sid="+Math.random();
            ajaxku.onreadystatechange=stateChanged;
            ajaxku.open("GET",url,true);
            ajaxku.send(null);
          }
    
          function buatajax(){
            if (window.XMLHttpRequest){
              return new XMLHttpRequest();
            }
            if (window.ActiveXObject){
              return new ActiveXObject("Microsoft.XMLHTTP");
            }
            return null;
          }
    
          function stateChanged(){
            var data;
            if (ajaxku.readyState==4){
              data=ajaxku.responseText;
              if(data.length>=0){
                document.getElementById("store").innerHTML = data
              }else{
                document.getElementById("store").value = "<select name=\"store\" class=\"form-control\">
             <option value=\"-1\"> - Choose Store -</option>
          </select>";
              }
            }
          }
        </script>
    

    StoreAPIService.php :

        session_start();
                $stores = array();
    
                $store_category_id = $_GET['category'];
    
                try 
                {
                    //$client = new GuzzleClient();
                    $response = $this->client->get('admin/store/bycat/rev/'.$store_category_id,
                        ['headers' => ['Authorization' => $_SESSION['login']['apiKey']]
                    ]);
    
                    $statusCode = $response->getStatusCode();
                    // Check that the request is successful.
                    if ($statusCode == 200) 
                    {
                        $error = $response->json();
                        echo "<select name=\"store\" class=\"form-control\">
    <option value=\"\">- Choose Store -</option>";
    
                        foreach ($error['stores'] as $store) 
                        {
                            $mainStore = new StoreSummary();
                            echo "<option value='{$mainStore->setStoreId($store['store_id'])};'>{$mainStore->setStoreName($store['store_name'])};</option>";
                            array_push($stores, $mainStore);
                        }//end of foreach
                      echo "</select>"
                    }
                }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c