【问题标题】:How to get a JSON Object in Python (Flask Framework)如何在 Python 中获取 JSON 对象(Flask 框架)
【发布时间】:2015-10-05 13:03:17
【问题描述】:

如何在 Python(Flask 框架)中获取 JSON 对象。 下面是我的代码sn-p `

var hotel=$( "#listHotel option:selected" ).val();      
        if(hotel!="select")
        {       
        $.ajax({
            url: '/getHotels',
            data: {'hotel':hotel},          
            type: 'POST',
            success: function(response){
                alert(response);
                var r= JSON.parse(response);                
                var rating =r.message               
                $("#rate").html("Ratings : "+rating);
                $("#rate").show('slow');                
                console.log(response);
            },
            error: function(error){
                alert(response);
                console.log(error);
              }
          });
        }`

如何在我的 Python 脚本 Flask Framework 中获取 JSON 值 hotel

from flask import Flask, render_template, json, request
app = Flask(__name__)

@app.route('/')
def main():
    return render_template('index.html')
@app.route('/getHotels',methods=['POST','GET'])
def getHotels():     
    try:        
        _hotel=request.POST['hotel']
        print _hotel

这是我的 Python 代码

【问题讨论】:

  • 你没有发送 JSON,所以 Flask 没有 JSON 可以获取。
  • 你在烧瓶中尝试过什么吗……如果你尝试了……那么你介意在这里展示一下吗?
  • 现在我用 Flask 中的 Python 代码提出了我的问题

标签: jquery python ajax json flask


【解决方案1】:

在您的 javascript 中将数据转换为 JSON 并将 contentType 设置为 "application/json"

data: JSON.stringify({'hotel':hotel}),
contentType : "application/json",

在您的烧瓶函数中,使用 request.json 获取 JSON:

@app.route('/getHotels')
def getHotels():
    hotel = request.json['hotel']
    .....

【讨论】:

    猜你喜欢
    • 2015-10-05
    • 2015-06-22
    • 2019-08-01
    • 2020-04-16
    • 1970-01-01
    • 2013-11-28
    相关资源
    最近更新 更多