我有一个 Flask 应用程序,带有一个小的客户端 javascript。我尝试使用 AJAX 将一个对象从我的 javascript 发送到在服务器端运行的 Flask 应用程序。但是,AJAX 请求是在我的 JavaScript 代码的其余部分运行之前发送的(注意:此代码应该在发送 AJAX 请求之前运行)。上网查了一下,原来是因为AJAX默认是异步的,但是$.ajaxSetup({async: false})并没有解决我的问题。
JS代码:
function submit(){
var no_of_subjects = parseInt(prompt("How many classes do you teach. NOTE: if you teach the same class two sujects, then consider it as 2 classes. If you are a class teacher and you teach that class a suject, then please count that class as well. (Enter a whole number)"))
var temp = ''
var subjects = []
for(var i=0;i<no_of_subjects;i++){
temp = prompt(`${i} class. Please enter the class name and section, followed by the subject you teach. For Example: 8D Biology, or 3C LifeSkills. Please leave no other spaces other than between the class name and the subject. The possible subjects can be refered in http://127.0.0.1:5000/help`)
subjects.push(temp)
}
var name = document.getElementById('name').value
var classteacher = document.getElementById('class_teacher').value
var teacher_id = docu.getElementById('teacher_id')
var msg = {
"name": name,
"class_teacher": classteacher,
"teacher_id": teacher_id,
"subjects": subjects
}
send_message(msg)
}
function send_message(msg){
$.ajaxSetup({async: false});
$.post("teacher_register", msg, function(){})
event.preventDefault()
}
HTML:-
<body>
<div class="center"><h1 class="rainbow">Register</h1></div>
<fieldset>
<legend>Fill in your credentials</legend>
<form>
Name : <input id="name" type="text"><br>
Are you a class teacher? If you are, type the class of which you are the classteacher of. If you aren't, type false. : <input id= class_techer type="text"><br>
Teacher id : <input id=teacher_id type="number"><br>
<br><button onclick="submit()">Submit</button>
</form>
</fieldset>
</body>
烧瓶(蟒蛇)代码:-
@app.route('/teacher_register', methods=["POST"])
def teacher_register():
data = request.get_json()
app.logger.debug(data)
return data
注意:我收到“类型错误:视图函数未返回有效响应”。该函数要么返回 None 要么在没有返回语句的情况下结束。作为代码运行时的错误。通过代码,我的意思是 Flask。这是因为数据里面没有任何价值,即它是 None
您编写的代码不会在其余代码之前运行 $.post(..) 函数。那是不可能的。事实是,覆盖表单提交行为是一团糟。尝试更改您的代码,以便<button>
在表单之外:
<form>
Name : <input id="name" type="text"><br>
Are you a class teacher? If you are, type the class of which you are the classteacher of. If you aren't, type false. : <input id= class_techer type="text"><br>
Teacher id : <input id=teacher_id type="number"><br>
<br>
</form>
<button onclick="submit()">Submit</button>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句