weixin_33726318 2015-02-05 17:10 采纳率: 0%
浏览 11

在javascript中输出html

I have been upgrading legacy pages to load data with AJAX.

The ajax call returns an object with custom properties

{ 
  item: {
    id: 1,
    name: 2,
   ...
  }
}

In my AJAX call I am building the elements

$.post("./url/returns-json", query, function(data) {
   var response = JSON.parse(data);
   $.each(response , function(i, v){
       var r = '<div class="style-this"><p>';
       var r += v.name;
       var r += '</p></div>';
       $("item-wrap").append(r);
   });
});

is there another way to wrap json response in HTML for display.

This method can get very untidy when building big HTML elements

  • 写回答

4条回答 默认 最新

  • weixin_33730836 2015-02-05 17:17
    关注

    The best approach might be this:

    $('#item-wrap').append(
      $('<div>').addClass('style-this').append(
        $('<p>').text(v.name)
      )
    );
    

    In my opinion, jQuery is actually great to dynamically build HTML structures. By indenting the code, the structure is visible very well and utility functions such as text allow you to insert content safely (see XSS).

    I assumed item-wrap was actually an element identifier, not a tag name. This does not affect my answer.

    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料