问题描述:
前端的值可以传到后端,但是后端的值无法传回前端;或者就是说ajax.success里面没有任何操作,但是后端又进行了操作,说明前端传到了后端但是后端传回前端出了问题。
造成这种问题可能有两个情况:
①ajax传的对象是在form中,查看(28条消息) 使用Ajax接收不到返回值???_qzxl的博客-CSDN博客_ajax接收不到返回值这篇文章,可以得知当ajax传的对象是在form中是自动把type设置为‘submit’的;
②后端传回前端的类型应该是ajax的datatype定好的类型...先开始没意识到这一点,在app.py中一直return ans(ans是一个字符串),导致前端一直收不到消息,后面改成
return json.dumps({'imgsrc': ans})
就好了。
下面是前端的代码:
js代码:
$('#xFile').change(function (e) {
var files = e.target.files;
var formFile = new FormData();
formFile.append("file", files[0]); //加入文件对象
$.ajax({
type: "POST",
url: "/upload",
data: formFile,
type: "post",
dataType: "json",
cache: false,//上传文件无需缓存
processData: false,//用于对data参数进行序列化处理 这里必须false
contentType: false, //必须
success:function(res){
console.log(111);
console.log(res);
var img = document.getElementById("imgPreview");
img.src = res["imgsrc"];
},
});
});
$("#sub").on('click',function(){
$.ajax({
type: "POST",
url:'/getData',
dataType:'json',
success:function(data) {
console.log(data);
}
});
});
app.py:
@app.route('/getData', methods=['POST', 'GET'])
def getdata():
return json.dumps({'msg': '这是一条测试信息', 'data': '这是一条有用的数据。'})
@app.route('/upload',methods=['POST','GET'])
def upload():
if request.method == 'POST':
f = request.files['file']
if not (f and allowed_file(f.filename)):
return jsonify({"error": 1001, "msg": "请检查上传的图片类型,仅限于png、PNG、jpg、JPG、bmp"})
basepath = os.path.dirname(__file__) # 当前文件所在路径
upload_path = os.path.join(basepath, 'static/images', f.filename) # 注意:没有的文件夹一定要先创建,不然会提示没有该路径
# upload_path = os.path.join(basepath, 'static/images','test.jpg') #注意:没有的文件夹一定要先创建,不然会提示没有该路径
f.save(upload_path)
ans = '../static/images/'+f.filename
print(ans)
#return render_template('index.html', imgsrc =ans)
return json.dumps({'imgsrc': ans})



