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

时间:2015-03-03 07:47:31

标签: php ajax

今天,我去编写一个带有动态下拉列表的表单。

使命:我想在用户选择类别时制作动态下拉列表,然后会出现具有该类别的商店。

形式为:

<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>

这是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>

这是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);
                }
            }
        }

我没有收到任何错误,但是商店有&#39;类别&#39;我选择的没有出现。

有人可以检查我是否出错了。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您试图更改下拉菜单的选项。我通过更改下拉菜单本身来做到这一点 我创建了一个div =&#34; store&#34;在html表单中并使用ajax

更改div的innerHTML

html表单

    <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代码

<!-- 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>"
                }
            }