javascript - 如何使用响应显示多个选定值

标签 javascript php jquery ajax checkbox

我正在尝试实现显示已存储的选定值。

我的问题是我正在尝试从 os_hostel_facility 映射表中获取多个设施 但是当我尝试显示只有第一个值出现在控制台中时,即使该值没有显示为选定的值,我该怎么做才能使我的代码位于底部:

如果问题未达到标准,请建议编辑..!

这是我的脚本:

   success: function (response) {
    $("#viewhostelfacility").val(response['facility']['id_facility']);
    console.log(response['facility']['id_facility']); 

here only first value is coming and i want to show the whole array as selected

这是我的更新表单代码

<ul id="hostel_facility" class="dropdown-menu dropdown-select">
    <?php  $facility = $conn->query("SELECT * FROM os_facilities  ORDER BY id_facility ASC");
        while ($facilityresult = $facility->fetch_assoc()) { ?>
        <li><a><input type="checkbox" name="hostel_facility[]" id="viewhostelfacility" value="<?php  echo $facilityresult['id_facility']; ?>" /><?php echo $facilityresult['facility_name']; ?></a></li>
    <?php } ?>
</ul>

这是我发送响应的 Controller 页面:

$facilitysearch= $conn->query("SELECT * From os_hostel_facility WHERE id_hostel='".$_POST['hostelId']."'") or die(mysql_error());
$viewfacility=$facilitysearch->fetch_assoc();
$response['facility'] = $viewfacility;

enter image description here enter image description here enter image description here

最佳答案

您可以创建一个each函数来获取数组中的所有数据:

success: function (response) {
    $.each(response,function(i,e)){
        $("#viewhostelfacility").val(e['facility']['id_facility']);
        console.log(e['facility']['id_facility']);
    }

向您发送 Json 对象?如果是,您可以使用数据标签轻松制作:

对象:

{"os_hostel":[
    {"facility":"Iron","id_facility":"1"},
    {"facility":"Landry","id_facility":"2"}
]}

代码

success: function (response) {
    var hostel = response.os_hostel;
    $.each(hostel,function(i,e){
        $("#viewhostelfacility").val(e.facility);
        console.log(e.facility);
    })

片段

var obj = {"os_hostel":[
  {"facility":"Iron","id_facility":"1"},
  {"facility":"Landry","id_facility":"2"}
]}

var hostel = obj.os_hostel;
$.each(hostel,function(i,e){
    console.log(e.facility);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

关于javascript - 如何使用响应显示多个选定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40104735/

相关文章:

javascript - 在基本 JavaScript 和 PHP 教程中无法获取事件中断器来阻止表单提交正常工作

jquery ajax 忽略 500 状态错误

javascript - Angular ng-if 确定输入数值

javascript - 使用 jQuery 应用 if 和 else 条件添加和删除类

javascript - jqueryui 替代方案

php - SQLquery 和 PHP 中的数组到字符串转换

javascript - 将日期文本(字符串)更改为日期格式 Javascript

javascript - firefox 使用 jQuery animate 方法和绝对位置的奇怪行为

javascript - Vue - 组件中无法访问商店模块

php - CentOS Linux 版本 8.0.1905 未更改 php.ini