2015-09-25 48 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); 

}