正在寻找更好的方法来设计使用AJAX检索的JSON对象数据的样式


Looking for better ways to style JSON object data retrieved using AJAX

我在我的网站上使用AJAX来获取由PHP脚本生成的JSON字符串。JSON对象看起来像:

{
  "people" : [
    { "name" : "Bob", "id" : "1", "sex" : "m" }, 
    { "name" : "Amy", "id" : "2", "sex" : "f" }
  ]
}

一旦我使用AJAX检索到它,我就会使用Javascript 手动设置它的样式

for(i = 0; i < obj.people.length; i++) {
  document.getElementById('people-container').innerHtml += '<span class=''' + obj.people[i].sex + ' person''>' + obj.people[i].name + '</span>
}

但我忍不住对在我的Javascript中嵌入HTML和类感到内疚,因为我对所有其他非AJAX内容都使用Smarty模板引擎

我想我不能用Smarty来处理我的AJAX响应,因为模板引擎在页面加载时运行,AJAX调用是在页面加载后完成的。。。有更好的方法吗?

如果您放入一些示例代码,这将非常有用。然而,如果我理解正确的话,我会使用我的AJAX调用来返回这样的东西:

{
  "html": "<span>...${sex}.. ${name}</span>",
  "people" : [
    { "name" : "Bob", "id" : "1", "sex" : "m" }, 
    { "name" : "Amy", "id" : "2", "sex" : "f" }
  ]
}

然后,您可以使用JS将标记附加到所需模板引擎的页面上。很明显,您也可以循环使用返回的数据,这将利用模板。

// Don't append more than once if multiple ajax calls
if ( !document.getElementById( 'people-template' ).length ) {
  // Append template to page
  var script = document.createElement('script');
  script.type = 'text/html';
  script.id = "people-template";
  document.body.appendChild( script );
}
for(i = 0; i < obj.people.length; i++) {
  // Using jQuery + jQuery templating here as an example
  // Never used smarty but I hope this shows you the idea well enough
  $('#people-container').innerHtml += $('#people-template').tmpl( obj );
}