简体   繁体   中英

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.

I am also using jquery to append the same li element to the list

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.

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

<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. You should just be able to append the HTML code directly without the need to build it again. 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.

It depends if you want to generate the HTML you are appending on the server side or the client side.

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. Then it will just call the server twice. But you will only have to maintain the code in one spot.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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