如何将复选框附加到我的ajax响应中

时间:2015-01-14 07:25:05

标签: jquery ajax

我正在尝试为从数据库接收的数据动态创建复选框。

jQuery和AJAX调用:

$("#destinationName").autocomplete({
    source : function(request, response) {
        $.ajax({
            url: "${pageContext.request.contextPath}/showDestinations",
            type: "POST",
            data : { term : request.term },
            dataType : "json",
            success : function(data) {
                alert(data);
            }
        });
    }
});
<label>Destination</label>
<input type="text" id="destinationName" name="destinationName" value="${Form.destinationName}" class="field" />

我保持警觉时收到的回复:

[ "abc", "def"]

请提供宝贵的建议。作为AJAX和jQuery的新手,我正面临着获得这个结果的艰难时期。

3 个答案:

答案 0 :(得分:1)

您可以尝试这样的事情

success: function(data) {
  $("#resultDiv").html("");
  $.each(data, function(i, record) {
    $("#resultDiv").append("<input type='checkbox' id='chk-" + i + "' name='" + record + "' /> " + record);
  });
}

答案 1 :(得分:0)

您可以尝试http://jsfiddle.net/4wf3rq04/

    use $.each(function(){...})

答案 2 :(得分:0)

您可以使用以下代码

success: function (data) {
                if (data.d != null) {

                    var temp = data.d;

                    if (temp != '') {

                        var Response = temp.split(",");

                        if ((Response != '') && (Response.length > 0)) {

                            for (i = 0; i < Response.length; i++) {
                                $("#resultDiv").append("<input type='checkbox' id='chk-" + i + "' name='" + Response[i] + "' /> " + Response[i]);

                            }
                        }

                    }
                }
            }