2013-03-09 59 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"] ;