简体   繁体   English

如何从ajax调用响应中添加html标签

[英]how to append a html tag from an ajax call response

I have an ajax function : 我有一个ajax功能:

$('#app-name').change(function () {//1
  console.log("inside change");
  var applname= this.value;
  console.log(applname);
  $.ajax({//2
    url: 'foo',
    method : 'GET',
    dataType : "json",
    contentType: "application/json",
    data: {"AppID":"appname"},
    success: function(data){
      var order_data = data;
      $('#foo-name').html('');
      $.each(order_data, function(i, item) {//3
        console.log(order_data[i]);
        $('<option value='+ order_data[i] +'>'+order_data[i]).html('</options>').appendTo('#foo-name');
      });//3 
    }
  });//2
});//1

This function is doing everything else except appending value to the html. 除了将值附加到html之外,此函数还执行其他所有操作。 Am i doing it wrong? 我做错了吗? Can you help solve this issues. 您能帮忙解决这个问题吗?

Place the closing </option tag in the jQuery object you create. 将结束</option标记放置在您创建的jQuery对象中。 Don't set it through the html() method. 不要通过html()方法进行设置。 Try this: 尝试这个:

$('<option value="' + order_data[i] + '">' + order_data[i] + '</option>').appendTo('#foo-name');

That said, you can also improve performance of your code by building the string in the loop and appending it to the select once, like this: 也就是说,您还可以通过在循环中构建字符串并将其附加到select一次来提高代码的性能,如下所示:

success: function(data) {
    var options = '';
    $.each(data.split(/\n/), function(i, item) {
        options += '<option value=' + item.trim() + '>' + item.trim() + '</option>');
    });
    $('#foo-name').html(options);
}

Update You also need to split() the text you state that you're returning before looping through it. 更新在循环浏览之前,您还需要对返回的文本进行split()

Please use below code in your ajax success event. 请在ajax成功事件中使用以下代码。

success: function(data) {
    var _html = '';
    $.each(order_data, function(i, item) {
        _html += '<option value='+ item +'>'+item+'</options>';
    });
    $('#foo-name').append(_html);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM