三生石@ 2016-12-16 19:56 采纳率: 100%
浏览 371

使用AJAX调用Flask API

I am experimenting with Flask and AJAX, I have a simple API route here , hosted at OpenShift. I want to call the API in a Javascript file with Ajax. The OpenShift Python file is simple:

from flask import Flask
app = Flask(__name__)

import json

@app.route('/hello/<name>')
def hello_world(name=None):
    str = {'key':'Hello World!', 'q':name}
    #out = {'key':str}
    res = json.dumps(str)
    return res

if __name__ == '__main__':
    app.run()

And here is the Ajax call:

$.ajax({
    type:"GET",
    dataType: "json",
    data:'Payam',
    url: "http://mypythonapp-spacepirate.rhcloud.com/hello/",
    success: function(data){
        buf1=data;
        console.log(data);
    }
})

But this makes a call to this url which results in 404. How can I solve this? Just to mention CORS is not an issue.

http://mypythonapp-spacepirate.rhcloud.com/hello/?Payam
  • 写回答

2条回答 默认 最新

  • weixin_33724059 2016-12-16 20:01
    关注

    Try changing your url property to

    url: "http://mypythonapp-spacepirate.rhcloud.com/hello/world",
    

    Then you will get a 200 response status, instead of the 404. The reason is the flask route you created has a required parameter after the hello/.

    edit: followup to question about using variable for the data

    • method1: just add encode the parameter to the url

      url: "http://mypythonapp-spacepirate.rhcloud.com/hello/" + encodeURIComponent(xyz)

    • method2: use the data parameter to the ajax call as you have started to do. I think that jquery will translate that into the URL query string for a get, like this. Notice the ? delimiting the start of query string:

      http://mypythonapp-spacepirate.rhcloud.com/hello/?xyz

      You can verify that by checking in your browser dev tools and seeing what URL the ajax call is actually requesting. Also note that in the flask handler you would then need to check for request.query_string to get the data, because <name> parameter would be empty.

    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?