2015-09-20 266 views
2

我在表單上有2個選擇菜單:類型和類別。當用戶從類型菜單中選擇一些內容時,我希望它執行一個查詢數據庫的PHP腳本,並返回所選類型的匹配類別列表供他們從類別菜單中選擇。AJAX將表添加到表單元格

這是行之有效的,但我現在想更新它,以便它添加類categoryGroup(「成功」或「錯誤」取決於AJAX結果)。這裏是我的表在2個單元:

<div class="form-group"> 
    <label for="title" class="control-label col-sm-3">Type</label> 
    <div class="input-group col-xs-8"> 
    <select class="form-control" name="type" id="type" onchange="getCategories(this.value)"> 
     <option value="" selected></option> 
     <option value="Business">Business</option> 
     <option value="Commercial">Commercial</option> 
     <option value="Commercial Land">Commercial Land</option> 
     <option value="Land">Land</option> 
     <option value="Rental">Rental</option> 
     <option value="Residential">Residential</option> 
     <option value="Rural">Rural</option> 
    </select> 
    </div> 
</div> 

<div class="form-group" id="categoryGroup"> 
    <label for="title" class="control-label col-sm-3">Category</label> 
    <div class="input-group col-xs-8" class="" id="categoryList"> 
    <select class="form-control" name="category" id="category"> 
     <option value="" selected></option> 
    </select> 
    </div> 
</div> 

,這裏是我的腳本,它的工作與AJAX調用適當的選項來代替類別選擇菜單:

<script type="text/javascript"> 
    function getCategories(str) { 
    if (str == "") { 
     document.getElementById("categoryList").innerHTML = ""; 
     return; 
    } 
    if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari 
     xmlhttp = new XMLHttpRequest(); 
    } else { // code for IE6, IE5 
     xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
    } 

    xmlhttp.onreadystatechange = function() { 
     if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { 
     document.getElementById("categoryList").innerHTML = xmlhttp.responseText; 
     } 
    } 

    xmlhttp.open("POST", "getPropertyCategories.php?type=" + str, true); 
    xmlhttp.send(); 
    } 
</script> 

我不知道如何更新這也是一類增加了categoryGroup ID

回答

0

很基本的,但我認爲你得到它的要點是:

xmlhttp.onreadystatechange = function() { 
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { 
     document.getElementById("categoryList").innerHTML = xmlhttp.responseText; 
    } 

    var status = xmlhttp.status == 200 ? 'success' : 'error' 
    var group = document.getElementById("categoryGroup") 
    group.classList.add(status) 
}