我真的很难理解我的代码发生了什么。目标是获取2个字符串并显示编辑距离。请求和响应必须作为JSON对象发送
这是我的index.html文件。
<html>
<head>
<meta charset="utf-8"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready( function() {
$('#mainForm').click(function() {
var formdata = $("#mainForm").serialize();
console.log(formdata);
$.ajax({
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({string1: $('#string1').val(), string2: $('#string2').val()}),
dataType: 'json',
url: '/index',
success: function (e) {
console.log(e);
window.location = "/index";
},
error: function(error) {
console.log(error);
}
});
});
});
</script>
</head>
<body>
<h1>Compute Edit Distance</h1>
<form action="/index" method='post' name="mainForm" id="mainForm">
String1: <input type="text" name="string1" id="string1">
</br>
</br>
String2: <input type="text" name="string2" id="string2">
</br>
</br>
<button name = "submit" id = "submit" name="submit">submit</button>
</br>
</br>
<span id="editDistance">{{edit_distance}}</span>
</form>
</body>
</html>
现在,当我切换$('#mainForm')时,点击$('#mainForm')。提交,不发送任何数据。如果我把它保持为.click我的控制器正确地接收JSON格式的数据,但这不是我想要的行为。只有在表单内单击时才会发送字符串,并且不显示edit_distance。如果我将其切换为提交,内容类型是application / x-www-form-urlencoded,我收到服务器错误。为什么会这样?另外,当我输入字符串时,如何动态显示编辑距离?
当我按下提交按钮时,请求JSON数据被设置为None。这是我的服务器代码。
@app.route('/index', methods=['GET', 'POST'])
def index():
edit_distance = 0
if request.method == 'POST':
print(request.content_type)
data = request.get_json()
string1 = data['string1']
string2 = data['string2']
print(string1, string2)
edit_distance = get_edit_distance(string1, string2, len(string1),len(string2))
print(edit_distance)
response = make_response(render_template('index.html', edit_distance = edit_distance))
return response
content-type是application / x-www-form-urlencoded,因为在执行ajax .onsubmit之后提交请求仍然存在。因此,您将看到交替的JSON和x-www-form-urlencoded请求。要解决此问题,您可以取消默认的提交行为:
//Prevent form submission from refreshing page
event.preventDefault();
至于如何动态更新它,你可以成功设置所需div的innerHTML,如下所示:
document.getElementById("divId").innerHTML = "desired value";