一、背景
JavaScript代码中有“img.src”变量:
img.src = path + '/' + inputImgName
后端路由想获取这个变量的值:
@bp.route('/twocata_segmented_image', methods=["GET"])
def twocata_new_segmented_image():
print("成功")
save_path = None # 初始化保存路径
from PIL import Image
from networks.unet import Unet
unet = Unet()
# if request.method == 'GET':
# print("这里是GET请求")
input_img_name = request.args.get('img.src') #这一行想获取img.src的值
print("获取从前端发送的inputImgName是:",input_img_name)
二、错误问题
没有直接将img.src
作为查询参数发送到后端。
在代码中,没有将img.src
直接作为数据的一部分发送到后端。它只是在前端生成了一个用于AJAX请求的img.src
值,但并没有直接将其作为查询参数发送到服务器。、
三、解决方法
要想将 img.src
的值传递到后端,需要通过前端向后端发出 HTTP 请求的方式发送它。
一种方法是使用 AJAX 向后端路由发送 GET 或 POST 请求,将 img.src
值作为请求的参数之一。
// 假设你想在点击按钮时将 img.src 的值发送到后端
$("#uploadBtn").on("click", function () {
var inputImgName = document.querySelector("#uploadImgName").value;
var imgSrc = path + '/' + inputImgName; // 获取 img.src 的值
// 发送 AJAX 请求到后端
$.ajax({
type: "GET", // 如果需要,更改为 "POST"
url: "/twocata_segmented_image",
data: { "img_src": imgSrc }, // 将 img.src 作为参数发送
success: function(response) {
console.log("后端回复:", response);
},
error: function(error) {
console.error("错误:", error);
}
});
});
在JS中,首先将path + '/' + inputImgName赋值给变量var“imgSrc”
再data: { "img_src": imgSrc }, 指定要发送到服务器的数据:这个地址将被作为键值对的值发送到服务器,键名是 "img_src"
。服务器端的代码可以通过获取 img_src
这个键的值来使用这个图片的地址信息。
最后在后端python代码中,获取“img_src”的值:
@bp.route('/twocata_segmented_image', methods=["GET"])
def twocata_new_segmented_image():
img_src = request.args.get('img_src')
print("从前端接收到的 img_src:", img_src)#这里这里~
# 根据需要处理 img_src
# ...
return "接收到的 img_src: " + img_src # 向前端返回一个响应
这样,当点击 #uploadBtn
时,将触发一个 AJAX 请求到你的后端路由 /twocata_segmented_image
,并将 img.src
的值作为名为 img_src
的参数发送。在后端,你可以使用 request.args.get('img_src')
来获取这个值