ajax笔记(flask后端)
使用jquery封装好的方法使用ajax
{% extends "base.html" %}
{% block page_content %}
<form id="uploadForm" enctype="multipart/form-data" >
<input type="file" name="image" id="img">
<img src="" id="show">
<input type="button" value="上传" id="upFileBtn">
<span id="predict"></span>
</form>
{% endblock %}
{% block scripts %}
{{ super() }}
<script type="text/javascript">
//图片预览
$("#img").change(function () {
var reader = new FileReader();
var img = document.getElementById("img");
var file = img.files[0];
reader.readAsDataURL(file);
reader.onload = function () {
document.getElementById('show').src = reader.result;
// console.log(reader.result);
}
})
$('#upFileBtn').click(function () {
var formFile = new FormData($("#uploadForm")[0]);
// 使用$.ajax发送post请求
$.ajax({
url:"/predict2",
type:"POST",
data:formFile,
processData:false,
contentType:false,
success:function (data) {
$("#predict").text(data.predictions[0]);
}
})
})
</script>
{% endblock %}
关于一些使用jquery的AJAX向服务器发送请求的坑
- 在使用版本较低的jquery的时候,发现向后端为flask的服务器发送和文件的时候会出现使用request.files获取不到文件的问题,经过一番查找,居然在request.data中发现获取到的文件信息,更换高版本的jquery后问题解决。