[英]AJAX request in Javascript is sent before the rest of my code
我有一个Flask应用程序,带有一个小的客户端javascript。 我试图使用AJAX将我的JavaScript的对象发送到在服务器端运行的flask应用程序。 但是,在运行我的JavaScript代码的其余部分之前,正在发送AJAX请求(注意:该代码应该在发送AJAX请求之前运行)。 在搜索Internet时,我了解到这是因为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>
FLASK(python)代码:-
@app.route('/teacher_register', methods=["POST"])
def teacher_register():
data = request.get_json()
app.logger.debug(data)
return data
注意:我收到'TypeError:视图函数未返回有效响应。 该函数返回None或不返回return语句而结束。 作为代码运行时的错误。 通过代码,我的意思是烧瓶。 这是因为数据内部没有任何值,即为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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.