使用JQuery追加将JSON项添加到HTML

时间:2017-11-27 13:43:25

标签: javascript jquery json

多个按钮具有类别名称(data-bcategory)。当我单击按钮时,基于该类别值使用ajax技能将从数据库中显示。我编写了一个函数,它将以下面的格式返回JSON。但在视图中,我想将每种技能的类别分开。我编写了每个函数并逐个显示技能值,但不是类别。我认为解决方案是分别编写另一个并显示类别名称。请检查预期结果和实际结果。

HTML

<div class="modal-body" id="ajaxdisplayskills"> </div>

JQuery的

<script type='text/javascript' language='javascript'>
  $(".boxselectcat").click(function () {
    var e = $(this).attr("data-bcategory")
    , l = $(this).attr("data-catgoid");
    $(".txtValueshwskillid").val(l), $.ajax({
     url: "<?php echo base_url(); ?>index/get_all_skills?category=" + e
     , type: "GET"
     , dataType: "json"
     , error: function () {
         $("#ajaxdisplayskills").append("<p>Some error please try again</p>")
     }
     , success: function (e) {
         $.each(e, function (e, l) {
            $("#ajaxdisplayskills").append('<label class="chkskills cursor1"><input class="hid" name="fr_skills" type="checkbox" value="' + l.id + '" />' + l.name + "</label>")
        })
      }
     })
    });
</script>

JSON

[
{
    "id": "95,100",
    "skill": "Car Washing,Sewage Cleaning",
    "sub_cat": "Cleaning"
},
{
    "id": "292",
    "skill": "Furniture Installation",
    "sub_cat": "Maintenance"
}
]

实际结果

<label class="chkskillsedit cursor1">
    <input class="hid" name="fr_skills" type="checkbox" value="95">Car Washing</label>
<label class="chkskillsedit cursor1">
    <input class="hid" name="fr_skills" type="checkbox" value="100">Sewage Cleaning</label>
<label class="chkskillsedit cursor1">
    <input class="hid" name="fr_skills" type="checkbox" value="292">Furniture Installation</label>

预期结果

<h4 class="signup-sub-cat">Cleaning</h4>
<label class="chkskillsedit cursor1">
    <input class="hid" name="fr_skills" type="checkbox" value="95">Car Washing</label>
<label class="chkskillsedit cursor1">
    <input class="hid" name="fr_skills" type="checkbox" value="100">Sewage Cleaning</label>
<h4 class="signup-sub-cat">Maintenance</h4>
<label class="chkskillsedit cursor1">
    <input class="hid" name="fr_skills" type="checkbox" value="292">Furniture Installation</label>

0 个答案:

没有答案