我的代码html如:
$.ajax({
type: "POST",
url: "hanca/hanca_crud.php",
dataType: 'json',
data: {
id_hanca: id_hanca,
type: "detail_hanca"
}, //detail_hanca
success: function(data) {
var teks = "";
$.each(data.detail, function(indeks, nilai) {
//status hanca
var tmp1 = nilai.status_detail_hanca;
$("select.status_detail_hanca").val(tmp1);
var no = nilai.no;
var status_detail_hanca = "<select class='status_detail_hanca' name='status_detail_hanca[]' ><option value='0'>Proses</option><option value='1'>Return</option><option value='2'>Selesai</option></select>";
teks += "<tr>" + no +
"</td><td>" + status_detail_hanca +
"</td></tr>";
});
$(".tbody_detail_hanca_checking").append(teks);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>No.</th>
<th>Status Proses</th>
</tr>
</thead>
<tbody class="tbody_detail_hanca_checking">
</tbody>
</table>
并输出json:
{
"detail": [{
"status_detail_hanca": "2",
"no": 1
}, {
"status_detail_hanca": "0",
"no": 2
}]
}
我使用ajax通过json获取数据,我想创建一个select option
并从json设置value
数据。但是,它不起作用。如何解决?
允许代码的文本虚拟 Lorem ipsum dolor坐下来,精神上的adipiscing elit。 Morbi vel fermentum massa,quis viverra lectus。 Aliquam tristique feugiat volutpat。 Donec elementum sapien vel enim facilisis sollicitudin。 Integer pellentesque volutpat enim
答案 0 :(得分:0)
$("select.status_detail_hanca").val(tmp1);
这不起作用,因为您在编写选择选项之前设置了选项 - $(".tbody_detail_hanca_checking").append(teks);
所以试试这个。
$.ajax({
type: "POST",
url: "hanca/hanca_crud.php",
dataType: 'json',
data: {
id_hanca: id_hanca,
type: "detail_hanca"
}, //detail_hanca
success: function(data) {
var teks = "";
$.each(data.detail, function(indeks, nilai) {
//status hanca
var tmp1 = nilai.status_detail_hanca;
$("select.status_detail_hanca").val(tmp1);
var no = nilai.no;
var status_detail_hanca = "<select class='status_detail_hanca' name='status_detail_hanca[]' >\n\
<option value='0'";
if(tmp1 === '0') {
status_detail_hanca += " selected ";
}
status_detail_hanca += ">Proses</option>\n\
<option value='1'";
if(tmp1 === '1') {
status_detail_hanca += " selected ";
}
status_detail_hanca += ">Return</option>\n\
<option value='2'";
if(tmp1 === '2') {
status_detail_hanca += " selected ";
}
status_detail_hanca += ">Selesai</option>\n\
</select>";
teks += "<tr>" + no +
"</td><td>" + status_detail_hanca +
"</td></tr>";
});
$(".tbody_detail_hanca_checking").append(teks);
}
});