我需要将大量PHP生成的HTML(5000 div元素)附加到文档片段并将其附加到页面正文。
示例HTML(这只是StackOverflow源的一部分,但它类似):
<div itemscope itemtype="http://schema.org/Article">
<link itemprop="image" href="http://cdn.sstatic.net/stackoverflow/img/apple-touch-icon.png">
<div id="question-header">
<h1 itemprop="name"><a href="/questions/4287357/access-php-variable-in-javascript" class="question-hyperlink">Access PHP variable in JavaScript [duplicate]</a></h1>
</div>
<div id="mainbar">
<div class="question" data-questionid="4287357" id="question">
<div class="everyonelovesstackoverflow" id="adzerk1">
</div>
<table>
<tr>
<td class="votecell">
<div class="vote">
<input type="hidden" value="4287357">
<a class="vote-up-off" title="This question shows research effort; it is useful and clear (click again to undo)">up vote</a>
<span class="vote-count-post ">2</span>
<a class="vote-down-off" title="This question does not show any research effort; it is unclear or not useful (click again to undo)">down vote</a>
<a class="star-off" href="#" title="This is a favorite question (click again to undo)">favorite</a>
<div class="favoritecount"><b>1</b></div>
</div>
我已将问题分解为两个较小的问题:
var tmp = "<?php Print($DOM); ?>";
我怎样才能让它发挥作用?
答案 0 :(得分:1)
我最近一直在使用jsrender来处理将大量JSON / Javascript数据格式化为HTML。这使我可以将更多数据打包到更少的字节中,然后让客户端使用模板创建大量的HTML。这是一个简单的例子:
<html><head>
<script type="text/x-jsrender" id="historyTemplate">
{{if orders}}
<h1>Your Order History</h1>
<table>
<thead>
<tr><th>Order Name</th><th>Amount</th><th>Status</th><th>Tracking</th></tr>
</thead>
<tbody>
{{for orders}}<tr>
<td><a href="{{>orderId}}" class="orderDetailLink">{{>orderName}}</a></td>
<td>{{>total}}</td>
<td>{{>status}}</td>
<td>{{if trackingNumber}}
<a target="_new" href="{{:trackingURL}}">{{>trackingNumber}}</a>
{{/if}}</td>
</tr>{{/for}}
</tbody>
</table>
{{else}}
<h1>You have no prior webstore orders.</h1>
{{/if}}
</script>
<script type="text/javascript">
var customer = {
name: 'Joe Bloe',
orders: [
{ orderName: 'Joe Bloe 2013/04/01 #595',
total: 59,
status: 'Not yet shipped',
trackingNumber: null,
trackingUrl: null
},
{ orderName: 'Joe Bloe 2013/04/15 #876',
total: 32.50,
status: 'Shipped',
trackingNumber: '55512345',
trackingUrl: 'http://www.shipper.com/track?55512345'
},
]
};
$("#orderDiv").html( $('#historyTemplate').render(customer) );
</script>
</head><body>
<h1>Your Order History</h1>
<div id="orderDiv"> </div>
</body></html>
数据在提供时可以是页面的一部分,也可以通过AJAX或JSONP到达,也可以由客户端自己动态生成。到目前为止,我从未遇到过性能问题。