简体   繁体   English

同时使用服务器端和javascript代码时如何避免多余的HTML代码

[英]How to avoid redundant HTML code when working with both serverside and javascript code

I have a basic list item that has an ID attribute with a value fetched from the database. 我有一个基本的列表项,该列表项的ID属性具有从数据库中获取的值。

I am also using jquery to append the same li element to the list 我也在使用jquery将相同的li元素追加到列表中

The problem that I am facing is that if I decide to add an attribute to the li element I am going to have to do it both on the server side code and the JavaScript code. 我面临的问题是,如果我决定向li元素添加一个属性,那么我将不得不在服务器端代码和JavaScript代码上都执行该操作。

I am not sure if any of you guys have ever faced this problem and came up with a solution. 我不确定你们中是否有人遇到过这个问题并提出了解决方案。 If so any help would be super appreciated. 如果是这样,任何帮助将是非常感谢。

Here is an example. 这是一个例子。 This is my php code.. this is just a quick and dirty example of how my real code looks like 这是我的php代码。.这只是我的真实代码看起来像的一个快速而肮脏的例子

<ul id="list_items">
foreach($todo_items as $todo_item{

   //Redundant html <li> tags... any change to the attributes I make here must be made in the jQuery code also to keep it consistent 
   echo "<li id='$todo_item->id'>$todo_item->item</li>";


}
</ul>

<script>

$(document).on("click",".add_todo", function(){

    $("add_new_item.php")

    .done(function(data){

      //A json return would come.. 

      //Redundant html li tags...
     $("#list_items").append("<li id='"+data.id+"'>Test</li>");

);

);

</script>

The code you're outputting from the php file is in the form of html. 您从php文件输出的代码为html格式。 You should just be able to append the HTML code directly without the need to build it again. 您应该只能够直接附加HTML代码,而无需再次构建它。 If you want to build it client side, you shouldn't need to echo html code out in the php, you can just use json_encode and send the values. 如果要在客户端构建它,则无需在php中回显html代码,只需使用json_encode并发送值即可。

It depends if you want to generate the HTML you are appending on the server side or the client side. 这取决于您是否要生成要在服务器端或客户端附加的HTML。

Hope it helps. 希望能帮助到你。

Edit: Sorry, I didn't read your code right the first time through. 编辑:对不起,我没有在第一时间就读完您的代码。 Probably the easiest way to do this is to use $get/$post. 可能最简单的方法是使用$ get / $ post。 Then it will just call the server twice. 然后它将仅调用服务器两次。 But you will only have to maintain the code in one spot. 但是您只需要将代码维护在一个位置即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM