简体   繁体   English

Ajax post多个数据到flask

[英]Ajax post multiple data to flask

The way I send one data to flask我发送一个数据到 flask 的方式

.js .js

function func(s) {

  let toPost = {name: f.name, sf: split.f};
  let jsonStr = JSON.stringify(toPost);
  $.ajax({
      url: "temp",
      type: "POST",
      data: JSON.stringify(data),
      processData: false,
      contentType: "application/json; charset=UTF-8",
      success: function(){
        console.log("success")
      }    
    });
}

.py .py

@app.route('/temp', methods = ['POST'])
def temp() :

    jsonStr = request.get_json()
    file_object = open('temp.txt', 'a')
    file_object.write(jsonStr)
    file_object.write("\n")
    file_object.close()

    return render_template('temp.txt')

But I would like to send multiple data, so the ajax look like this:但是我想发送多个数据,所以 ajax 看起来像这样:

data: {str: JSON.stringify(data), method: "add"}

Everything else remains the same.其他一切都保持不变。

In the.py file how could I get both str and method as well?在 .py 文件中,我怎样才能同时获得strmethod呢?

errors错误

console安慰

jquery-3.2.1.min.js:4          POST FILENAME 400 (BAD REQUEST)

com com

127.0.0.1 - - [] "POST /FILENAME HTTP/1.1" 400 -

full error完全错误

在此处输入图像描述 在此处输入图像描述

Your code leaves a lot of room for speculation.您的代码留下了很大的猜测空间。
The error message you get results from the fact that you want to send data as JSON but do not format it completely compliantly.您收到的错误消息是由于您希望将数据作为 JSON 发送,但没有完全符合格式。

Normally, submitted objects are automatically sent as form data and formatted accordingly beforehand.通常,提交的对象会自动作为表单数据发送,并预先进行相应的格式化。 You suppress this behavior by setting the processData parameter to false .您可以通过将processData参数设置为false来抑制此行为。 However, this also means that the formatting to JSON must also be done by you.但是,这也意味着格式化为 JSON 也必须由您完成。 Otherwise a string representation of the transferred object would be sent, which the server cannot interpret.否则将发送传输的 object 的字符串表示,服务器无法解释。

As the following example shows, you should convert all data to JSON using JSON.stringify(...) before sending it.如以下示例所示,您应该在发送之前使用JSON.stringify(...)将所有数据转换为 JSON。

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Index</title>
    <style media="screen">
      output {
        white-space: pre;
      }
    </style>
  </head>
  <body>
    <form name="my-form">
      <input type="text" name="name" />
      <input type="text" name="sf" />
      <input type="submit" />
    </form>
    <output name="result"></output>

    <script
      src="https://code.jquery.com/jquery-3.6.0.min.js"
      integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
      crossorigin="anonymous"></script>

    <script type="text/javascript">
      $(document).ready(() => {
        $('form[name="my-form"]').submit(function(evt) {
          evt.preventDefault();
          const form = $(this);

          const formData = {};
          $.each(form.serializeArray(), (_, row) => {
            formData[row.name] = row.value;
          });
          // => { name: <anything>, sf: <something> }
          console.log(formData);

          const method = 'add';
          const data = { data: formData, method: method };
          // => { data: { name: <anything>, sf: <something> }, method: "add" }
          console.log(data);

          $.ajax({
            url: '/temp',
            type: 'post',
            data: JSON.stringify(data),
            contentType: 'application/json; charset=utf-8',
            processData: false
          }).done(data => {
            $('output[name="result"]').html(data);
          });
        });
      });
    </script>
  </body>
</html>

Depending on the requirements, you can query the data on the server side using its key, since it has already been parsed from the JSON format.根据需要,你可以在服务器端使用它的键查询数据,因为它已经从 JSON 格式解析出来了。
Since you get a dict for your nested object because of this, a conversion to a string is necessary before you can write it to the file.由于您因此获得了嵌套 object 的dict ,因此在将其写入文件之前需要转换为字符串。

import json, os
from flask import (
    Flask, 
    render_template,
    request
)

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/temp', methods=['POST'])
def temp():
    data = request.json.get('data')
    method = request.json.get('method', 'add')
    if method == 'add' and data:
        path = os.path.join(app.static_folder, 'temp.txt')
        with open(path, 'a') as fp:
            print(json.dumps(data), file=fp)
    return app.send_static_file('temp.txt')

Please note that this is a simplified example trying to be based on your specifications.请注意,这是一个试图基于您的规格的简化示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM