Flask的Ajax发布请求


                    

我正在使用AJAX将POST请求发送到Flask路由,但我不知道如何以我可以阅读的格式获取发布数据。</ p>

我的路线如下:</ p>

  @ app.route(“ / sendinvites”,methods = [“ POST”])
@要求登录
def sendinvites():
     打印(request.get_data(“电子邮件”))
     返回jsonify(“ done”)
</ code> </ pre>

我的AJAX外观为:</ p>

  $。ajax({
     输入:“ POST”,
     dataType:“ json”,
     网址:“ / sendinvites”,
     数据:{电子邮件:电子邮件,用户名:用户名},
     成功:功能(数据){
       console.log(数据)
     }
   });
</ code> </ pre>

在emails变量中发送的数据的示例是:</ p>

  0:对象{id:未定义,用户名:“ me@mydomain.com”}
</ code> </ pre>

该路线的输出示例为:</ p>

  b'emails%5B0%5D%5Busername%5D = me%40mydomain.com'
</ code> </ pre>

有人知道我如何将帖子数据放入字典对象中,以便于处理吗?</ p>
     </ div>

展开原文

原文

I am using AJAX to send a POST request to a Flask route, but I don't know how to get the post data in a format I can read.

My route looks like this:

@app.route("/sendinvites", methods=["POST"])
@login_required
def sendinvites():
    print(request.get_data("emails"))
    return jsonify("done")

My AJAX looks as:

$.ajax({
    type: "POST",
    dataType: "json",
    url: "/sendinvites",
    data: { emails : emails, usernames: usernames  },
    success: function(data) {
      console.log(data)
    }
  });

An example of the data sent in the emails variable is:

0: Object { id: undefined, username: "me@mydomain.com" }

An example of the output from the route is:

b'emails%5B0%5D%5Busername%5D=me%40mydomain.com'

Does anyone know how I can get the post data into a dictionary object so it is easier to process?

1个回答


有很多方法可以做到这一点,但首先,请确认请求中包含有效的JSON。</ p>


  1. request.get_json()</ code> </ li>
    </ ol>

      request.get_json(silent = True)
    </ code> </ pre>

    设置 silent = True </ code>时, get_json </ code>函数在尝试检索JSON正文时将无提示地失败。 默认情况下,它设置为 False </ code>。</ p>


    1. jsonify(request.json)</ code> </ p> </ li>
      </ ol>

      这将返回整个 request </ code>对象。 您必须通过在发送Ajax代码中的 request </ code>时指定发布的密钥来提取所需部分。</ p>

      请参阅Flask部分的相关内容,线程 </ p>

      请参阅Ajax部分线程 </ p>
           </ div>

展开原文

原文

There are many ways to do this, but first, verify that the request contains a valid JSON.

  1. request.get_json()
request.get_json(silent=True)

With silent=True set, the get_json function will fail silently when trying to retrieve the JSON body. By default, this is set to False.

  1. jsonify(request.json)

This will return the entire request object. You'll have to extract the required part by specifying the key posted while sending the request in your ajax code.

Refer this for Flask part, thread

Refer this for Ajax part, thread

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