【发布时间】:2019-03-21 16:30:51
【问题描述】:
我正在创建一个 Web 表单,其中一个两个字段是 datetime 数据类型。然后我通过 AJAX 将此表单数据传递给服务器。下面是代码 JQuery sn-p。
$(document).ready(function(){
$('#btnSubmit').click(function(){
var start = $("#start").val();
var end = $("#end").val();
$.ajax({
type:'POST',
url: '/interuption',
data: $('#formint').serializeArray(),
success: function(response){
alert(response);
},
error: function(error){
console.log(error);
}
});
});
});
关联的HTML如下:
<form id = "formint" class="myForm" method= "post" action="/interuption">
<th>
<label>Start Time Stamp
<input id = "start" type="datetime-local" name="start_timestamp" required>
</label>
</th>
<th>
<label>End Time Stamp
<input id ="end" type="datetime-local" name="end_timestamp" required>
</label>
</th>
</form>
在服务器端,我使用的是 Flask。我正在使用request.form.get 方法来检索datetime。然后我试图将它推送到 MS SQL Server。下面是 Python 代码 sn-ps。
cnxn = pyodbc.connect(#credentials)
cursor=cnxn.cursor()
query_insert = "INSERT INTO test.dbo.testFeed(start_timestamp,end_timestamp)
VALUES (?,?)"
@app.route('/interuption',methods = ['GET','POST'])
def interuption():
try:
data_1 = datetime.datetime.strptime(request.form.get('start'),%Y-%m-%d %H-%M-%S')
data_2 = datetime.datetime.strptime(request.form.get('end'),%Y-%m-%d %H-%M-%S')
if data_1 and data_2:
cursor.execute(query_insert,(data_1,data_2))
cnxn.commit()
cnxn.close()
return json.dumps({'status':'OK'})
else:
return json.dumps({'error':'data has not been insterted!!'})
except Exception as e:
return json.dumps({'excp':str(e)})
return render_template('form.html')
当我运行上述代码时,我收到如下错误
{"excp": "time data 'None' does not match format '%Y-%m-%d %H-%M-%S'"}
显然request.form.get 没有从网络表单中获取任何价值。
我怎样才能摆脱这个?
【问题讨论】: