三生石@ 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 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发