1
我需要知道什麼更好/更高效,當我的頁面加載時我需要從數據庫加載一些元素。現在我使用php在腳本標記中生成正確的JS。使用php生成腳本或使用json
它看起來是這樣的
<script type="text/javascript">
canvas = $('#drawn').get(0)
c = canvas.getContext('2d');
<? foreach ($projectArray[1] as $shape): ?>
<?
switch ($shape['type']):
case 1: ?>
c.beginPath();
c.moveTo(<?=$shape['x_points'][0] ?>, <?=$shape['y_points'][0] ?>);
<? for ($point = 0; $point < count($shape['x_points'])-1; $point++): ?>
c.lineTo(<?=$shape['x_points'][$point] ?>, <?=$shape['y_points'][$point] ?>);
<? endfor; ?>
c.stroke();
<? break;
...
此頁面的底部是很長,看起來像這樣生成的腳本。
script type="text/javascript">
canvas = $('#drawn').get(0)
c = canvas.getContext('2d');
c.beginPath();
c.moveTo(373, 138);
...
c.lineTo(586, 242);
c.lineTo(588, 243);
c.lineTo(589, 244);
c.stroke();
c.beginPath();
c.moveTo(222, 165);
c.lineTo(222, 165);
...
c.lineTo(313, 309);
c.lineTo(261, 309);
c.stroke();
c.beginPath();
c.moveTo(81, 110);
c.lineTo(81, 110);
c.lineTo(84, 110);
...
正如你可以看到這個基於基於我從一個數據庫拉PHP通過陣列上很長的腳本。在我心底深處,這感覺就像做錯了一樣,而應該將數組編碼爲json,並將其作爲json對象進行迭代。
真的,我的問題是,生成一個這樣的腳本是否應該使用json,以及使用json有什麼優勢?
JSON。你正在重複'c.lineTo('就像十億次,所以在你的服務器上解析一堆數字和一個函數分隔符會更容易。 – Blender 2011-04-25 01:42:45
要麼你必須運行c.lineTo(很多它只是如果我在一個對象的for循環中運行它,或者我從一個長生成的腳本運行它 – austinbv 2011-04-25 01:53:47
不,Blender在說什麼,它反覆創建多個字符串'c.lineTo'需要更多的過程密集併發送該腳本給用戶),而不是發送原始數據數組,並在javascript中進行數值迭代。在PHP中做的越少,您的應用程序就會越好地與用戶擴展。 – GAgnew 2011-04-25 04:25:14