天天看點

Python全棧 Web(Ajax JSON JQuery)

JOSN:

    Javascript Object Notation

    作用:

        主要限制前後端互動資料的格式

    JSON的格式

        表示單個對象

            使用{}  采用鍵值對的格式儲存資料

            鍵必須使用雙引号引起來

            相當于Python的字典

        表示多個對象

            使用[]表示一個數組

            數組中允許包含多個字元串或對象

jQuery中的循環:

    $arr.each(function(i, obj)){

        $arr:表示jQuery中的數組

        i:表示目前元素的下标

        obj:表示的是目前元素

    };

    $.each(arr,function(i, obj){

        arr:表示jQuery中的數組

    });

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <script src="/static/js/common.js"></script>
  <script src="/static/js/jquery-1.11.3.js"></script>
  <script>
    $(function(){
      /*為#btn綁定click事件*/
      $("#btn").click(function(){
        //1.建立xhr
        var xhr = createXhr();
        //2.建立請求
        xhr.open('get','/json',true);
        //3.設定回調函數
        xhr.onreadystatechange=function(){
          if(xhr.readyState==4&&xhr.status==200){
            var resText = xhr.responseText;
            /*console.log(typeof(resText));
            console.log(resText);*/

            //将resText 轉換為 JSON對象
            var arr = JSON.parse(resText);
            // 循環
            $.each(arr,function(i,obj){
              console.log(obj.name);
              console.log(obj.age);
              console.log(obj.gender);
            });

          }
        }
        //4.發送請求
        xhr.send(null);
      });
    });
  </script>
</head>
<body>
  <button id="btn">JSON</button>
</body>
</html>           

    背景處理JSON

    在背景查詢出資料再轉換為JSON的格式字元串  再響應

    給前端  到前端後再将字元串轉換為JS對象

        1.背景擷取資料

            類型允許為 元祖,清單、字典

        2.在背景将資料轉換為符合JSON格式的字元串

        3.在背景将JSON格式的字元串進行響應

        4.在前端将JSON格式的字元串解析成JS對象

@app.route('/json_users')
def json_users():
  user = Users.query.filter_by(id=1).all()
  list = []
  for u in user:
    list.append(u.to_dict())
  return json.dumps(list)


@app.route('/01-users')
def users_01():
  return render_template('01-users.html')
           

    在Python中的JSON處理

        元祖、清單、字典、隻用Python中的json類就可以

        import json

        jsonstr = json.dumps(資料結構)

        return jsonstr

@app.route('/json')
def json_views():
  list = ["Fan Bingbing","Li Chen","Cui Yongyuan"]
  dic = {
    'name':'Bingbing Fan',
    'age' : 40,
    'gender':'female',
  }

  uList = [
    {
      'name': 'Bingbing Fan',
      'age': 40,
      'gender': 'female',
    },
    {
      'name' : "Jinbao Hong",
      'age' : 70,
      'gender' : 'male'
    }
  ]
  jsonStr = json.dumps(uList)
  return jsonStr           

    在前端中處理JSON

        由于在伺服器響應回來的資料是string

        有些時候必要将響應回來的資料轉換為JS對象或數組

        在js中

            JSON對象 = JSON.parse(JSON字元串)

var arr = JSON.parse(resText);           

JQuery AJAX

    在jQuery中  提供了原生的AJAX的封裝

    $obj.load(url, [data], [callback])

        作用:

            異步加載資料到$obj元素中

        參數:

            URL:異步請求位址

            data:傳遞給服務端的參數  可以傳遞字元串,JSON對象

            callback: 異步請求完成後要執行的操作 (回調函數)

            function(resText, statusText){

                resText:響應資料

                statusText:響應的狀态文本

            }

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
  <button id="btnLoad">使用load方法加載</button>
  <div id="show"></div>
  <script src="/static/js/jquery-1.11.3.js"></script>
  <script>
    $(function(){
      $("#btnLoad").click(function(){
        //var params = "name=sf.zh&age=85";
        var params = {
          "name":'yinsusu',
          "age":25,
        }
        $("#show").load(
          '/03-server',
          params,
          function(resText,statusText){
            /*console.log("resText:"+resText);
            console.log("statusText:"+statusText);*/

            $(this).html("<h1>"+resText+"</h1>");
          });
      });
    });
  </script>
</body>
</html>           
@app.route('/03-load')
def load_views():
  return render_template('03-load.html')

@app.route('/03-server',methods=['POST'])
def server_03():
  name = request.form.get('name')
  age = request.form.get('age')
  return "姓名:%s,年齡:%s" % (name,age)
           

    $.get(url, [data], [callback], [type])

        url:異步請求位址

        data:請求送出的資料 可以是字元串,json對象

        callback:請求成功時的回調函數

        function(resText){

            resText:響應後來的文本

        }

        type:

            響應回來的資料類型

            HTML:響應回來的文本是HTML文本(預設)

            text:響應回來的文本是普通文本

            json:響應回來的文本是json對象

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
  <button id="btnGet">發送get請求</button>
  <div id="show"></div>

  <script src="/static/js/jquery-1.11.3.js"></script>
  <script>
    $(function(){
      $("#btnGet").click(function(){
        $.get('/04-server',function(resText){
          /*console.log("type:"+typeof(resText));
          console.log(resText);*/
          $.each(resText,function(i,obj){
            console.log(obj.id + ":" + obj.cityname);
          });
        },'json');
      });
    });
  </script>
</body>
</html>           
@app.route('/04-get')
def get_views():
  return render_template('04-get.html')

@app.route('/04-server')
def server_04():
  cities = City.query.all()
  list = []
  for city in cities:
    list.append(city.to_dict())
  return json.dumps(list)