Python全棧 Web(Ajax JQuery-AJAX 跨域請求)



jQuery對AJAX的支持
$.ajax()
語法:
$.ajax({請求參數的json對象});
請求參數對象的屬性:
URL:字符串 表示異步請求地址
type:字符串 請求方式 get或post
date:傳遞到服務端的參數 參數字符串("name=dfh&age15")或json
datetype:響應回來的數據格式
HTML
xml
text
script
json
jsonp:有關跨域的響應了格式
success:
回調函數 響應成功後的回調函數
error:
回調函數 請求或響應失敗時的回調函數
beforSend:
回調函數 發送AJAX請求之前的回調函數
如果return False 則終止請求發送


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-1.11.3.js"></script>
</head>
<body>
    <h1>靜態網頁</h1>

    <p>
        uname <input type="text" id="uname">
    </p>
    <button id="btnajax">查詢</button>
    <p id="show"></p>
    <script>
        $(function () {
            $("#btnajax").click(function () {
                // 使用get請求發送一個uname參數 到服務器
                $.ajax({
                    // 請求地址
                    url: "/05-server1",
                    // 請求方式
                    type: "get",
                    // 請求參數
                    data: "uname=" + $("#uname").val(),
                    // 響應回來的數據格式
                    dataType: 'json',
                    // 請求和響應後的回調函數
                    success: function (data) {
                        if (data.id){
                            // 如果data中有ID屬性 說明查詢成功
                            var html = "";
                            html += "<h3> id:" + data.id + "</h3>";
                            html += "<h3> uname:" + data.uname + "</h3>";
                            html += "<h3> upwd:" + data.upwd + "</h3>";
                            html += "<h3> realname:" + data.realname + "</h3>";

                        } else {
                            // 否則查詢失敗
                            html += "<h3>" + data.msg + "</h3>";
                        }
                        $("#show").html(html)
                    }
                });
            });
        });
    </script>
</body>
</html>



@app.route("/05-server1")
def server_05_views():
    uname = request.args.get("uname")
    u = Users.query.filter_by(uname=uname).first()
    if u:
        return json.dumps(u.to_dict())
    dic = {
        "status": "0",
        "msg": "not username"
    }
    return json.dumps(dic)


跨域(Cross Domain)
什麼是跨域?
HTTP協議中有一個策略 "同源策略"
同源:
多個地址中 相同的協議 相同的域名 相同的端口
在HTTP中 必須是同源地址中 必須是同源地址才能相互
發送請求 非同源拒絕請求(<script>和<img>除外)

非同源的網頁相互發送請求的過程就是跨域
跨域只能接受GET請求 不能接受POST請求
跨域解決方案:
通過<script>標記向服務器發送請求
由服務器資源指定前端頁面的那個方法來執行響應的數據
jQuery的跨域:
jsonp json with padding
$.ajax({
url:"xxx",
type: "get",
dataType:'jsonp', //指定跨域訪問
jsonp: "callback", //定義了callback函數名 以便於callback傳遞過去的函數名
jsonpCallback:'xxx' //定義了傳遞過去函數的名字 jsonp的回調函數
});



<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-1.11.3.js"></script>
</head>
<body>
    <button id="btn">跨域請求</button>
    <div id="show"></div>
    <script>


        function show(data){
            console.log(data);
        }

        $(function () {
           $("#btn").click(function () {
               // 無法完成跨域訪問
               // var url = "http://127.0.0.1:5000/06-server"
               // $.get("/06-server", function (data) {
               //     $("#show").html(data)
               // });

               // 原生js完成跨域請求
               // 獲取body標記
               var body = document.getElementsByTagName("body")[0];
               // 動態創建script標記
               // 通過script請求響應回來的數據一律當成js腳本來執行
               var script = document.createElement("script");
               // 設置script的type屬性  可以省略
               script.type = "text/javascript";
               // 網絡請求地址
               // callback 參數告訴後端 前端處理響應數據的函數名
               script.src = "http://127.0.0.1:5000/06-server?callback=show";
               // 將標記追加到當前頁面  也就是向src的地址發送請求同時接受響應數據
               // 響應數據直接交給了頁面 頁面將響應數據當成js腳本程序執行
               body.append(script);
           });
        });
    </script>
</body>
</html>



@app.route("/06-server")
def server_06():
    # 接受前端傳遞過來的數據 也就是前端自定義的函數名
    fun = request.args.get("callback")
    # 響應數據 被前端當成js腳本執行
    return fun + "('server 06')"





三種形式的跨域請求



<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-1.11.3.js"></script>
</head>
<body>
    <button id="btnShow">顯示</button>
    <div id="show"></div>
    <script>
        function flight(data) {
            html = "";
            html += "<h3> 航班  " + data.flight + "</h3>";
            html += "<h3> 出發  " + data.from + "</h3>";
            html += "<h3> 到達  " + data.to + "</h3>";
            html += "<h3> 時間  " + data.time + "</h3>";
            $("#show").html(html);
        }
        $(function () {
           $("#btnShow").click(function () {
               // 原生跨域請求
               // var body = document.getElementsByTagName("body")[0];
               // var script = document.createElement("script");
               // script.type = "text/javascript";
               // script.src = "http://127.0.0.1:5000/07-server?callback=flight";
               // body.append(script);

               // jQuery跨域請求 jsonp
               // $.ajax({
               //     url: "http://127.0.0.1:5000/07-server",
               //     type: "get",
               //     dataType: "jsonp",
               //     jsonp: "callback",
               //     jsonpCallback: "flight"
               // });

               // jQuery跨域請求 jsonp
               $.ajax({
                   url:'http://127.0.0.1:5000/07-server',
                   type:'type',
                   dataType:'jsonp',
                   success:function (data) {
                       console.log(data.flight);
                       console.log(data.from);
                       console.log(data.to);
                       console.log(data.time);

                   }
               });

           });
        });
    </script>


</body>
</html>






@app.route("/07-server")
def server_07():
    cb = request.args.get("callback")
    dic = {
        "flight": "MU763",
        "from": "beijing",
        "to": "saipan",
        "time": "16:55"
    }
    return cb + "(" + json.dumps(dic) + ")"


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章