使用AJAX调用Flask API


                    

我正在实验Flask和AJAX,我有一条简单的API路由此处 ,托管在OpenShift。 我想使用Ajax在Javascript文件中调用API。 OpenShift Python文件很简单:</ p>

从烧瓶导入烧瓶的

 
app = Flask(__ name__)

导入json

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

如果__name__ =='__main__':
     app.run()
</ code> </ pre>

这是Ajax调用:</ p>

  $。ajax({
     类型:“ GET”,
     dataType:“ json”,
     数据:“ Payam”,
     网址:“ http://mypythonapp-spacepirate.rhcloud.com/hello/”,
     成功:功能(数据){
         buf1 =数据;
         console.log(data);
     }
})
</ code> </ pre>

但这会调用此URL,结果为404。如何解决此问题? 只是说CORS并不是问题。</ p>

  http://mypythonapp-spacepirate.rhcloud.com/hello/?Payam
</ code> </ pre>
     </ div>

展开原文

原文

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个回答


尝试将您的url属性更改为</ p>

  url:“ http://mypythonapp-spacepirate.rhcloud.com/hello/world”,
</ code> </ pre>

然后,您将获得200的响应状态,而不是404。原因是您创建的烧瓶路由在hello /之后具有必需的参数。</ p>

编辑:有关对数据使用变量的问题的后续行动</ p>


  • 方法1:只需将参数编码添加到url </ p>

    URL:“ http://mypythonapp-spacepirate.rhcloud.com/hello/” + encodeURIComponent(xyz)</ code> </ p> </ li>

  • 方法2:在开始使用ajax调用时,请使用 data </ code>参数。 我认为</ em>,jquery会将其转换为URL查询字符串,以获取 get </ code>,如下所示。 请注意?</ code>分隔查询字符串的开头:</ p>

    http://mypythonapp-spacepirate.rhcloud.com/hello/?xyz </ code> </ p>

    您可以通过签入浏览器开发工具并查看ajax调用实际请求的URL来进行验证。 还要注意,在烧瓶处理程序中,您将需要检查request.query_string以获取数据,因为 </ code>参数将为空。 </ p> </ li>
    </ ul>
         </ div>

展开原文

原文

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.


使用 Alex G Rice 提供的指南,并在此处Python Flask如何从URL获取参数?我发现如何直接按以下方式传递数据:</ p>

Ajax调用:</ p>

  $。ajax({
     类型:“ GET”,
     dataType:“ json”,
     数据:{'name':'Payam'},
     网址:“ http://mypythonapp-spacepirate.rhcloud.com/hello/”,
     成功:功能(数据){
         buf1 =数据;
         console.log(data);
     }
})
</ code> </ pre>

python文件:</ p>

  @ app.route('/ hello /',methods = ['GET','POST'])
def hello_world(name = None):
     buf1 = request.args.get('name')
     str = {'key':'Hello World!','q':buf1}
     #out = {'key':str}
     res = json.dumps(str)
     返回资源
</ code> </ pre>
     </ div>

展开原文

原文

Using the guidelines provided by Alex G Rice and the answers here Python Flask how to get parameters from a URL? I found out how to pass the data directly as following:

The Ajax call:

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

The python file:

@app.route('/hello/', methods=['GET','POST'])
def hello_world(name=None):
    buf1 = request.args.get('name')
    str = {'key':'Hello World!', 'q':buf1}
    #out = {'key':str}
    res = json.dumps(str)
    return res

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问