【发布时间】:2020-04-17 16:38:45
【问题描述】:
我正在尝试使用 Fetch api 将一些带有 Javascript 的 HTML 表单输入传递到服务器端(Flask)。当我发送 POST 请求时,它运行良好,我也可以接收数据,但它也在 Mozilla Firefox 上给了我这个错误声明:
SyntaxError:“JSON.parse:JSON 数据的第 1 行第 1 列出现意外字符”
在谷歌浏览器上它给了我:
SyntaxError: Unexpected token
这是我的 Fetch api 代码:
$(document).ready(function() {
const myForm = document.getElementById("vform");
myForm.addEventListener('submit', function(e){
let phonenumber = document.getElementById('phoneNumber').value;
let password = document.getElementById('password').value;
let checked = document.getElementById('rememberMe').value;
if(typeof phonenumber, password, checked !== 'undefined' && phonenumber, password, checked !== null) {
var data = [{
phoneNo: phonenumber,
password: password,
checked: checked,
}];
fetch(`${window.origin}/login`, {
method:'POST',
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
})
.then((res) => res.json())
.then((data) => console.log(data))
.catch((err)=>console.log(err))
e.preventDefault();
}
});
});
这就是我在服务器端接收数据的方式:
@app.route("/login", methods=["GET", "POST"])
def login():
if request.get_json() != None:
req = request.json()
phoneNo = req["phoneNo"]
password = req["password"]
checked = req["checked"]
print(phoneNo)
return render_template("index.html", req=req)
为什么会这样?你能帮帮我吗?
【问题讨论】:
-
大部分时间无效字符是
<意味着响应是html。您可以在尝试解析它之前 console.log 值以验证 -
您的
login()函数正在渲染index.html,这可能是 HTML,而不是 JSON。
标签: javascript json forms flask fetch-api