我將一個資料發送到燒瓶的方式
.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
@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:
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?
errors
console
jquery-3.2.1.min.js:4 POST FILENAME 400 (BAD REQUEST)
com
127.0.0.1 - - [] "POST /FILENAME HTTP/1.1" 400 -
full error

uj5u.com熱心網友回復:
您的代碼留下了很大的猜測空間。
您收到的錯誤訊息是因為您希望將資料作為 JSON 發送,但不完全符合格式要求。
通常,提交的物件會自動作為表單資料發送并預先進行相應的格式化。processData您可以通過將引數設定為 來抑制此行為false。但是,這也意味著 JSON 的格式化也必須由您完成。否則將發送傳輸物件的字串表示,服務器無法解釋。
如以下示例所示,您應該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>
根據要求,您可以使用其密鑰在服務器端查詢資料,因為它已經從 JSON 格式決議。
由于您因此獲得了dict嵌套物件的 a,因此必須先轉換為字串,然后才能將其寫入檔案。
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')
請注意,這是一個嘗試基于您的規范的簡化示例。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/442771.html
標籤:javascript python jquery ajax flask
