2013-03-09 34 views
0

我如何可以加载成功JSON响应之后的图像?加载图像响应

jQuery的

$.post('@Url.Action("Upload", "Camera")', { 
    type: 'data', 
    image: canvas.toDataURL("image/png") 
}, function (result) { 
    if(result.success) { 
    alert('The image was successfully sent to the server for processing'); 

    var $image = $("<img src='~/temp/" + @ViewData["CaputredImage"] + "'/>"); 
    $image.live("load", function() { 
     $("#imageContainer").append(this); 
    }); 

    } 
}); 

图像容器

<div id="imageContainer"></div> 

回答

1

我可能会包括路径的JSON新提交的图像从服务器发回,然后:

$.post('@Url.Action("Upload", "Camera")', { 
    type: 'data', 
    image: canvas.toDataURL("image/png") 
}, function (result) { 
    if(result.success) { 
    alert('The image was successfully sent to the server for processing'); 

    // *** Change is on next line *** 
    var $image = $("<img src='" + result.imagePath + "'/>"); 
    // *** Another change on the next line *** 
    $image.on("load", function() { 
     $("#imageContainer").append(this); 
    }); 

    } 
}); 

另请注意,我将live呼叫更改为on。这不是第一次使用live的正确方法,其次它已被弃用了一段时间,现在实际上已被删除。

另外,你有一个竞争条件存在(虽然在这种情况下,一个是不太可能实际上会导致您的问题):你是不是后挂钩load事件的图像,直到您指定的src。虽然JavaScript的浏览器上是单线程的(除非您使用网络工作者),该浏览器。如果它已经在缓存中的图像(再次,不太可能在这种情况下),它可以触发事件load你把它挂  —前,看到没有连接到事件处理程序,它不排队其运行时的JavaScript是下一次闲置。

而且(在另一极端),你就等着给图像添加到文档中它的加载后,直到;我不是100%确定所有浏览器都会加载图像,如果它不在任何文档中。

因此,对于它的价值:

$.post('@Url.Action("Upload", "Camera")', { 
    type: 'data', 
    image: canvas.toDataURL("image/png") 
}, function (result) { 
    if(result.success) { 
    alert('The image was successfully sent to the server for processing'); 

    // *** Changes start here *** 
    var $image = $("<img>"); 
    $image.css({ 
     position: "absolute", 
     left: -10000, 
     top: 0 
    }); 
    $image.attr("src", image.imagePath); 
    $image.appendTo(document.body); 
    $image.on("load", function() { 
     $image.remove(); 
     $("#imageContainer").append("<img src='" + result.imagePath + "'>"); 
    }); 
    // *** End of changes *** 
    } 
}); 

这将创建一个img元素关闭网页,但在文件中,挂钩图像加载,设置src,并在负载下降是有利于新img元素创建一个没有应用CSS的CSS。 (您可以将这些呼叫链接在一起,为了清晰起见将它们分开。)

+0

不工作!事情是我不认为'负载'会在json响应后在这里工作 – 2013-03-10 06:26:02

+0

@JackManson:当然会。一个与另一个无关。必须有其他事情正在进行。 – 2013-03-10 14:11:49

0
var img = new Image(); 
img.onload = function() { 
    $("#imageContainer").append(img); 
}); 
img.src ='~/temp/' + @ViewData["CaputredImage"] ;