今天,我開始編寫一個包含Dynamic dropwdown列表的表單。AJAX 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);
}
}
}
我沒有錯誤,但我選擇的「類別」商店沒有出現。
任何人都可以請檢查我是否出錯。
感謝您的幫助。
轉到開發工具,進入網絡選項卡,並檢查Respo通過AJAX調用的第一部分來查看你回來的內容。 – Barmar 2015-03-03 07:52:30