JSON & aJax 練習

In this example below you will see how to do a JSON & aJax 練習 with some HTML / CSS and Javascript

Thumbnail
This awesome code was written by uncleben006, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright uncleben006 ©

Technologies

  • HTML
  • CSS
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>JSON & aJax 練習</title>
  
  
  
      <link rel="stylesheet" href="css/style.css">

  
</head>

<body>

  
<h2>JSON與ajax的結合</h2>
<h4>JSON.parse(文字)->物件結構</h4>
<div class="todolist">
  <h3>我的代辦清單</h3>
  <hr/>
  <ul id="listitem"></ul>
</div>
  <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js'></script>

  

    <script  src="js/index.js"></script>




</body>

</html>

/*Downloaded from https://www.codeseek.co/uncleben006/json-andamp-ajax-andx7df4andx7fd2-eRdzRE */
@charset "UTF-8";
* {
  font-family: 微軟正黑體;
}

body {
  padding: 30px;
}

.todolist {
  display: inline-block;
  padding: 20px;
  border: solid 1px;
}
.todolist ul {
  padding: 0;
}
.todolist li {
  list-style: none;
  width: 300px;
}

.done:before {
  content: "✓";
  color: red;
}


/*Downloaded from https://www.codeseek.co/uncleben006/json-andamp-ajax-andx7df4andx7fd2-eRdzRE */
var item_template="<li class='{{class}}'>{{num}}.{{name}}({{date}})</li>";

var data_url="https://awiclass.monoame.com/api/command.php?type=get&name=tododata";

var tododata;

$.ajax(
  {
    url: data_url,
    success: function(res){
      tododata = JSON.parse(res);
      for(var i=0; i<tododata.length; i++){
        var item = tododata[i];
        //如果item.done等於true,就把done指定給now_class,不然now_class就是空白
        var now_class=(item.done==true)?"done":"";
        

        var now_item = 
            item_template.replace("{{name}}",item.name)
                         .replace("{{num}}",i+1)
                         .replace("{{date}}","date:"+item.date)
                         .replace("{{class}}",now_class);
        
        $("#listitem").append(now_item);
      }
    }
  }
);

Comments