我正在用getJSON填充选择菜单。我想知道是否有一种方法可以使用jQuery的.each函数引入这些值?
当然,必须有一种更简单的方法来完成此操作……也许吗?
PHP文件:
<?php $queryMonth = "SELECT monthID, month FROM months"; $result = $db->query($queryMonth); while($rowMonth = $db->fetch_assoc($result)) : $data[] = $rowMonth; endwhile; echo json_encode($data); ?>
jQuery:
$.getJSON('selectMenus.php', function(data) { $("select.month").append("<option value=" + data[0].monthID + ">" + data[0].month + "</option>"); $("select.month").append("<option value=" + data[1].monthID + ">" + data[1].month + "</option>"); $("select.month").append("<option value=" + data[2].monthID + ">" + data[2].month + "</option>"); $("select.month").append("<option value=" + data[3].monthID + ">" + data[3].month + "</option>"); $("select.month").append("<option value=" + data[4].monthID + ">" + data[4].month + "</option>"); $("select.month").append("<option value=" + data[5].monthID + ">" + data[5].month + "</option>"); $("select.month").append("<option value=" + data[6].monthID + ">" + data[6].month + "</option>"); $("select.month").append("<option value=" + data[7].monthID + ">" + data[7].month + "</option>"); $("select.month").append("<option value=" + data[8].monthID + ">" + data[8].month + "</option>"); $("select.month").append("<option value=" + data[9].monthID + ">" + data[9].month + "</option>"); $("select.month").append("<option value=" + data[10].monthID + ">" + data[10].month + "</option>"); $("select.month").append("<option value=" + data[11].monthID + ">" + data[11].month + "</option>"); });
我的json输出看起来像这样:
[{ "monthID": "1", "month": "January" }, { "monthID": "2", "month": "February" }, { "monthID": "3", "month": "March" }, { "monthID": "4", "month": "April" }, { "monthID": "5", "month": "May" }, { "monthID": "6", "month": "June" }, { "monthID": "7", "month": "July" }, { "monthID": "8", "month": "August" }, { "monthID": "9", "month": "Septemeber" }, { "monthID": "10", "month": "October" }, { "monthID": "11", "month": "November" }, { "monthID": "12", "month": "December" }]
使用@RaYell的方法....这对我有用:
$.getJSON('months.php', function(data){ var html = ''; var len = data.length; for (var i = 0; i < len; i++) {html += '<option value="' + data[i].monthId + '">' + data[i].month + '</option>'; } $('select.month').append(html); });
感谢大家在此方面的帮助!