从服务器和/或客户端加载动态元素的典型技术是什么


What is the typical technique of loading dynamic elements from the server and/or client?

假设我有一个简单的表单设置。我可以通过javascript将下面的元素作为mant时间动态添加到表单中。

<div class="aComplicateDiv">
    <input type="text" name="myValue">
</div>

现在假设我们保存这些值,然后想要编辑它们。我可以在编辑页面上查询DB,然后从服务器端显示带有输入字段的div。

我的问题是,当我添加这个div时,我使用javascript来构建元素。然而,当我在服务器端显示这些元素时,我使用的是php。似乎是重复的,尤其是如果我想改变元素的话。然而,我可以从服务器端调用javascript函数,这些函数通过编辑页面上的javascript传递值来构建它,但这似乎不是正确的过程。如果有没有更好的方法,任何见解都会很好。

我主要在这种情况下使用的方法(尤其是当重复部分变得更复杂时):

在PHP中(极度简化):

function addRow($index, $data) {
    echo '<div class="aComplicateDiv" id="row-'.$index.'">
              <input type="text" name="myValue['.$index.']" value="'.htmlspecialchars($data).'">
          </div>';
}
foreach($dataFromDb as $row) {
    addRow($row['id'], $row['value']);
}
addRow('TEMPLATE', '');

在Javascript(演示)

var nextIndex = 2; // Find a way to calculate this
$('#add').click(function() {
    // Append a clone of the template to a temporary div
    // From that div we can get the html-content
    var html = $('<div>').append(
        $('#row-TEMPLATE').clone()
    ).html().replace(/TEMPLATE/g, nextIndex++);
    $('#row-TEMPLATE').before(html);
});