2015-09-25 79 views
0

我有以下的jQuery腳本whic從數據庫作爲JSON檢索數據:JQuery的追加數據到一個HTML選擇標籤

$(document).ready(function() { 
    $.ajax({ 
    type: "GET", 
    url: "database/Emarps/websrvc/websrvc.php?task=getData&UUID=" + currentuuid + "&DataGt=hk", 
    dataType: "JSON", 
    success: function(response) { 
     $('#PrevOptns').val(response[0].hiv_prev); 
     $('#HivTrans').val(response[0].hiv_trans); 
    } 
    }); 

}); 

我怎樣才能通過數據來反映或以下HTML選擇標籤附加(選擇標記接受多個選擇和返回的數據可以多一個一個選擇):

<select required name="HivTrans" id="HivTrans" size="7" multiple class="select_with_label_wide"> 

    <option id="Handshake and close body contact">Handshake and close body contact</option> 
    <option id="Mosquito's and other insects">Mosquito's and other insects</option> 

    <option id="Kissing">Kissing</option> 
    <option id="Sharing of needles/Syringes">Sharing of needles/Syringes</option> 
    <option id="Other">Other</option> 
</select> 

<select required name="PrevOptns" id="PrevOptns" size="7" multiple class="select_with_label_wide"> 

    <option id="Avoid mosquito bites">Avoid mosquito bites</option> 
    <option id="Get protection from traditional healer">Get protection from traditional healer</option> 
    <option id="Other">Other</option> 
    <option id="Don't know">Don't know</option> 
</select> 
+0

你能在這裏發表JSON響應 – dreamweiver

回答

0
$("#PrevOptns").append('<option value='+response[0].hiv_prev+'>'+response[0].hiv_prev+'</option>'); 
    $("#HivTrans").append('<option value='+response[0].hiv_trans+'>'+response[0].hiv_trans+'</option>'); 
    $('#PrevOptns').trigger("chosen:updated"); 
    $('#HivTrans').trigger("chosen:updated"); 
0

如果要追加的所有數據,嘗試「每個」循環做。

$(document).ready(function() { 
    $.ajax({ 
    type: "GET", 
    url: "database/Emarps/websrvc/websrvc.php?task=getData&UUID=" + currentuuid + "&DataGt=hk", 
    dataType: "JSON", 
    success: function(response) { 
     for (var i=0; i<response.length; i++) { 
     $('#PrevOptns').append('<option value='+response[i].hiv_prev+'>'+response[i].hiv_prev+'</option>');; 
     $('#HivTrans').append('<option value='+response[i].hiv_trans+'>'+response[i].hiv_trans+'</option>'); 
     } 
    } 
    }); 

}); 
0

jQuery有一個append方法,您可以使用它來將內容插入html元素的末尾。建立你的元素,並簡單地將它們附加到相關的選擇標籤。

JS

success: function (response) { 
    var prevOpts = "<option value='" +response[0].hiv_prev +"'</option>"; 
    var hivTrans= "<option value='" +response[0].hiv_prev +"'</option>"; 

    $("#PrevOptns").append(prevOpts); 
    $("#HivTrans").append(hivTrans); 

}