article

Thursday, January 21, 2021

Python Flask Read XML with jQuery Ajax

Python Flask Read XML with jQuery Ajax app.py
#app.py
from flask import Flask, render_template

app = Flask(__name__)
             
@app.route('/')
def index():
    return render_template('index.html')
    
if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Python Flask Read XML with jQuery Ajax</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
  <script>
  $(document).ready(function () {
      $.ajax({
          type: "GET",
          url: "/static/music.xml",
          dataType: "xml",
          success: function_Parsxml
      });
  });
  function function_Parsxml(xml) {
      $('#load').fadeOut();
      $(xml).find("mostplayedsongs").each(function () {
          $(".main").append('<div class="song"><div class="title">' + $(this).find("Title").text() + '</div> <div class="Artist">' + $(this).find("Artist").text() + '</div></div>');
          $(".song").fadeIn(1000);
      });
  }
  </script>
  <style>
  .main{
  width:100%;
  margin:0 auto;
  }
  .song{
  width:208px;
  float:left;
  margin:10px;
  border:1px #dedede solid;
  padding:5px;
  display:none;
  }
  .title{
  margin-bottom:6px;}
  .Artist{font-size:12px; color:#999; margin-top:4px;}
  </style>
  </head>
  <body>
  <p><h2>Python Flask Read XML with jQuery Ajax</h2></p>
  <div class="main">
      <div align="center" class="loader"><img src="/static/img/loader.gif" id="load" align="absmiddle"/></div>
  </div>
  </body>
  </html>
 
static/music.xml
//static/music.xml
<?xml version="1.0" encoding="utf-8" ?>
<musictype>
<mostplayedsongs>
<Title>Sexyback</Title>
<Artist>Timberlake, Justin</Artist>
</mostplayedsongs>
 
<mostplayedsongs>
<Title>Wonderful Tonight</Title>
<Artist>Clapton, Eric</Artist>
</mostplayedsongs>
 
<mostplayedsongs>
<Title> Amazed</Title>
<Artist>Lonestar</Artist>
</mostplayedsongs>
 
</musictype>

Related Post