Ajax跨域访问Flask构建的Python Web服务器

看到标题,你可能会觉得作者比较奇葩,为什么要把事情搞得这么复杂?其实作者也不想这样,只是去年已经用PHP搭建好了系统,而且功能、UI等也基本调试的差不多了;现在要借助Python强大而方便的数据分析功能来分析数据,最简单直接的也就是这么做了。或许之后,会考虑用Django等来重构整个系统,但这并不是现在的重点。

利用Ajax跨域访问Flask服务器

Web前端通过Ajax请求Flask服务器的接口:

<script type="text/javascript">
    $(document).ready(function(){
        $("#click_demo").click(function(){
            //http request
            $.post("http://127.0.0.1:8080/demo",
            {
               name:$("#param").text(),
            },
            function(data,status){
                //alert("status:" + status + "\ndata:" + data);
                var myobj=eval(data);
                var result='';
                for (var i = 0;i < myobj.length;i++) {
                    var item='<p>'+myobj[i].name+'</p>';
                    result=result+item;
                }
                $("#result-element")[0].innerHTML=result;
                $("#result-element").show();
            });
        });
    });
</script>

Ajax跨域请求的时候可以在服务端设置header信息,来达到跨域请求的目的(不需要通过jsonp的方式设置ajax参数):

Response.AddHeader("Access-Control-Allow-Origin", "*");

Flask服务器端代码如下:

@app.route('/demo', methods=['POST'])
def home():
    result_json = json.dumps(result)
    # Response
    resp = Response(result_json)
    resp.headers['Access-Control-Allow-Origin'] = '*'
    return resp

Python操作Json

JSON (JavaScript Object Notation), specified by RFC 7159 (which obsoletes RFC 4627) and by ECMA-404, is a lightweight data interchange format inspired by JavaScript object literal syntax (although it is not a strict subset of JavaScript).

import json

list1 = [20, 6, 15, 53, 47]
list2 = [(6, 'John', '20'), (20, 'David', '21'), (47, 'Amy', '23'), (15, 'Kim', '18'), (53, 'Mary', '20')]

list3 = []
for a in list2:
    dict = {}
    dict['id'] = a[0]
    dict['name'] = a[1]
    dict['age'] = a[2]
    list3.append(dict)
result = {}
result['id'] = list1
result['data'] = list3

json1 = json.dumps(list1)
json2 = json.dumps(list2)
json3 = json.dumps(list3)
json4 = json.dumps(result)
print(json1)
print(json2)
print(json3)
print(json4)

decode = json.loads(json4)
print(decode)

JS解析Json数据

<SCRIPT LANGUAGE="JavaScript">
    var t="{'firstName': 'cyra', 'lastName': 'richardson', 'address': { 'streetAddress': '1 Microsoft way', 'city': 'Redmond', 'state': 'WA', 'postalCode': 98052 },'phoneNumbers': [ '425-777-7777','206-777-7777' ] }";
    var jsonobj=eval('('+t+')');
    alert(jsonobj.firstName);
    alert(jsonobj.lastName);


    var t2="[{name:'zhangsan',age:'24'},{name:'lisi',age:'30'},{name:'wangwu',age:'16'},{name:'tianqi',age:'7'}] ";
    var myobj=eval(t2);
    for(var i=0;i<myobj.length;i++){
        alert(myobj[i].name);
        alert(myobj[i].age);
    }

    var t3="[['14113295100','社旗县国税局桥头税务所','社旗县城郊乡长江路西段']]";
    //通过eval()函数可以将JSON字符串转化为对象
    var obj = eval(t3);
    for(var i=0;i<obj.length;i++){
        for(var j=0;j<obj[i].length;j++){
            alert(obj[i][j]);
        }
    }
</SCRIPT>

参考资料:

Ajax跨域请求

How do I set response headers in Flask?

Flask API

Python操作json的API

JS解析json数据(如何将json字符串转化为数组)

    原文作者:八宝粥BBZ
    原文地址: https://www.jianshu.com/p/cefa62235946
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞