Flask提供json api跨域訪問,ajax接收json資料

來源:互聯網
上載者:User

標籤:json   返回   function   python   ati   跨域   .com   object   4.0   

ajax在判斷請求成功時會判斷返回的資料是否為json,需要將response的content-type設定為application/json,資料為標準的json格式

jQuery版本

<script src="https://cdn.bootcss.com/bootstrap/4.0.0-beta/js/bootstrap.min.js"></script>

flask程式碼範例

@app.route(‘/test‘,methods=[‘GET‘,‘POST‘])def test():    a = []    a.append(Newobject().__dict__)    #設定content-type    resp=Response(json.dumps(a),mimetype=‘application/json‘)    #支援跨域請求    resp.headers[‘Access-Control-Allow-Origin‘] = ‘*‘    return resp

  

ajax樣本,請求返回的結果為result,一個json轉換後的對象

$.ajax({                url:"http://192.168.11.130/test",                type:‘GET‘,                dataType:‘JSON‘,               success:function (result) {                    console.log("ajax succeed")                   console.log(typeof(result))                    obj=result;                    var pcapdata=‘‘;                    for(var i=0;i<obj.length;i++)                    {                        pcapdata=pcapdata+‘<tr>‘                        pcapdata=pcapdata+‘<td>‘+obj[i].time+‘</td>‘;                        pcapdata=pcapdata+‘<td>‘+obj[i].srcip+‘</td>‘;                        pcapdata=pcapdata+‘<td>‘+obj[i].dstip+‘</td>‘;                        pcapdata=pcapdata+‘<td>‘+obj[i].httphost+‘</td>‘;                        pcapdata=pcapdata+‘<td>‘+obj[i].requesturi+‘</td>‘;                        pcapdata=pcapdata+‘<td>‘+obj[i].pcapfile+‘</td>‘+‘</tr>‘;                    }                    document.getElementById("td1").innerHTML=pcapdata;                    }            })

  

Flask提供json api跨域訪問,ajax接收json資料

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.