Asp.net mvc 为什么第一个代码段会触发image.onload,而第二个不会触发?
这会触发img.onload。然而:Asp.net mvc 为什么第一个代码段会触发image.onload,而第二个不会触发?,asp.net-mvc,jquery,Asp.net Mvc,Jquery,这会触发img.onload。然而: function SetImage(planViewCanvas, context, componentID) { var img = new Image(); img.onload = function () { alert("Fired!!"); planViewCanvas.width = img.width; planViewCanvas.height = img.height;
function SetImage(planViewCanvas, context, componentID) {
var img = new Image();
img.onload = function () {
alert("Fired!!");
planViewCanvas.width = img.width;
planViewCanvas.height = img.height;
context.drawImage(img, 0, 0, img.width, img.height);
$('#NoPlanViewImage').hide();
}
$.ajax({
url: '../PlanView/RenderFloorPlanImage',
data: { ComponentID: componentID },
datatype: 'json',
success: function (imageSource) {
if (imageSource !== "") {
img.src = '../PlanView/RenderFloorPlanImage?ComponentID=' + componentID;
}
}
});
}
修改ajax请求s.t.I将src设置为返回的数据是不可能的。我希望在不必再次返回控制器的情况下设置映像,但我还希望在映像完全加载后触发onload事件。这是如何实现的
$.ajax({
url: '../PlanView/RenderFloorPlanImage',
data: { ComponentID: componentID },
datatype: 'json',
success: function (imageSource) {
if (imageSource !== "") {
img.src = imageSource;
}
}
});
我想更好的问题可能是“如何将文件加载到图像中?”当我设置src属性时,它似乎会自动为我完成,但当我获得结果句柄时,它不会自动完成。您正在流式传输图像的二进制文件。在AJAX调用中不能将其设置为SRC。服务器将发送一个MIME类型,然后流式传输文件。Ajax调用需要一个路径,然后浏览器将自己获取文件
i、 e.请求需要文本/HTML作为响应,但会得到意外的图像MIME头+二进制数据。您的浏览器无法加载图像,因此不会触发任何
onload
。
src=
属性必须设置为有效的URI,而不是原始png数据。想想如果你把原始的PNG文件放在HTML文件上会发生什么。难怪它坏了
在某种程度上,您可以通过Base64编码图像并使用所谓的
data:
url来进行欺骗。我不确定跨浏览器对此的支持有多好。据我所知,internet explorer是一个合适的URI吗?如果它是404,我想它不会触发一个onload
,从您共享的内容判断,我会假设它是一个对象,甚至不是一个字符串。对不起,我刚刚添加了控制器操作。我正在返回一个文件对象。请尝试console.log(imageSource)
。确实有有效的JSON对象吗?如果您试图发送二进制数据,这将非常棘手。您需要一些Base64编码。console.log试图输出PNG文件。我的控制台中填充了不可渲染的ascii字符。原始PNG数据对于src=
属性无效。这意味着要设置为URL。事实上。您知道直接设置src是否是最佳做法吗?这里的问题是,我不想总是返回一个映像,但是如果我自动尝试将返回值放入src,我无法很好地检测控制器是否返回null。除了映像之外,您还会返回什么?服务器被赋予了一个ID,它正在寻找与该ID相关联的楼层平面图。我不需要为没有楼层平面图的ID设置“默认”图像,只想在页面上显示/隐藏警告。当我从RenderFloorPlanImage返回null时,imageSource等于“”。最好返回:“../PlanView/RenderFloorPlanImage?ComponentID=1234”。检查有效的ID。如果找不到占位符URL,请发回。我觉得这不正确。。。如果我去服务器一次——服务器不应该返回img检索图像所需的路径。当服务器可能只是返回一个压缩图像时,这是额外的RTT。我是否没有正确地跟踪您?如何确定src将返回一个有效映像,而不会两次点击服务器?在我看来,您似乎可以加载映像,然后等待触发onload
,或者发生超时(当src无效时)。
public ActionResult RenderFloorPlanImage(int componentID)
{
PlanViewComponent planViewComponent = PlanViewServices.GetComponentsForPlanView(componentID, SessionManager.Default.User.UserName, "image/png");
MemoryStream memoryStream = null;
if (!Equals(planViewComponent, null))
{
FloorPlan floorPlan = GetDesktopFloorPlan(planViewComponent);
// get the floor plan for the desktop...
if (!Equals(floorPlan, null) && !Equals(floorPlan.Image, null) && floorPlan.Image.Length > 0)
{
memoryStream = new MemoryStream(floorPlan.Image);
}
}
return !Equals(memoryStream, null) ? File(memoryStream, "image/png") : null;
}