将Ajax Request的响应图像设置为img标记

时间:2015-07-23 14:21:40

标签: jquery html ajax image

我有来自服务器的图像我试图将其添加为图像标记,但我遇到的问题是我的代码:

        $.ajax({
            type: "get",
            url: "SOME_IMAGE_URL",
            contentType: "image/png",
            success: function (data) {
           var img = new Image();
                var url = window.URL || window.webkitURL;
                img.src = url.createObjectURL(data);
            document.getElementById("createThingicon").appendChild(img);
            },
        });

当响应的图像被附加到HTML时,它不会显示它是一个破碎的图像。我的代码中有什么问题吗?我对URL进行了硬编码,以便您可以检查响应

1 个答案:

答案 0 :(得分:1)

$.ajax({
     type: "get",
     url: "Your_Remote_URL",
     mimeType: "text/plain; charset=x-user-defined",
     success: function (data) {

         $image = $('<img />').attr('src', 'data:image/png;base64,' + base64encode(data));
         $('#createThingicon').append($image);

     },
 });

function base64encode(str) {
    var CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    var out = "", i = 0, len = str.length, c1, c2, c3;
    while (i < len) {
        c1 = str.charCodeAt(i++) & 0xff;
        if (i == len) {
            out += CHARS.charAt(c1 >> 2);
            out += CHARS.charAt((c1 & 0x3) << 4);
            out += "==";
            break;
        }
        c2 = str.charCodeAt(i++);
        if (i == len) {
            out += CHARS.charAt(c1 >> 2);
            out += CHARS.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));
            out += CHARS.charAt((c2 & 0xF) << 2);
            out += "=";
            break;
        }
        c3 = str.charCodeAt(i++);
        out += CHARS.charAt(c1 >> 2);
        out += CHARS.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
        out += CHARS.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
        out += CHARS.charAt(c3 & 0x3F);
    }
    return out;
}