【问题标题】:convert reponse of jquery ajax call (need to handle 404 error for gravtar) for getting gravatar into image source转换 jquery ajax 调用的响应(需要处理 gravatar 的 404 错误)以将 gravatar 转换为图像源
【发布时间】:2016-06-22 14:21:42
【问题描述】:

这是我的代码:

var hashEmail = md5.createHash(email);

$.get("http://www.gravatar.com/avatar/" + hashEmail + "?d=404")
                        .then(function(response) {
                            var data = 'data:image/jpeg;base64,' + response;
                            $('.result').html('<img src="' + data + '" class="img-circle"/><span class="username username-hide-mobile" ng-bind="'+ attributes.name +'"></span>'); 
                        }, function(response) {
                           return defaultProfileImage();
                        });

我得到的响应如下:

**

������%10JFIF�%01%01��%01�%01������;创建者:gd-jpeg v1.0(使用 IJG JPEG v80),质量 = 90���C �%03%02%02%03%02%02%03%03%03%03%04%03%03%04%05%08%05%05%04%04%05%07%07%06% 08%0C%0C%0C%0B%0B%0B%0E%12%10%0E%11%0E%0B%0B%10%16%10%11%13%14%15%15%15%0C% 0F%17%18%16%14%18%12%14%15%14...C%01%03%04%04%05%04%05%05%05%14%0B%14%14% 14%14%14%14%14%14%14%14%14%14%14%14%14%14%14%14%14%14%14%14%14%14%14%14%14% 14%14%14%14%14%14%14%14%14%14%14%14%14%14%14%14%14%14%14%14%14%14%14���%11 %08�P�P

**

我无法将此响应转换为图像源。我做错什么了吗?这是我已经尝试过的:

// var binaryData = [];

// binaryData.push(response);

// var img = new window.Image();

// img.src = window.URL.createObjectURL(response);

// scope.imageUrl = img.src;

// scope.imageUrl = (window.URL || window.webkitURL).createObjectURL(img);

// scope.imageUrl = window.btoa(unescape(encodeURIComponent(response)));

// let blob = new Blob([response], { type: 'image/jpeg' });

// scope.imageUrl = (window.URL || window.webkitURL).createObjectURL(blob);

// scope.imageUrl = response;

//返回scope.imageUrl;

也尝试使用 angular $http 服务调用,但遇到了 CORS 问题,因此有人建议使用 Jquery Ajax 调用

【问题讨论】:

  • 你为什么要使用ajax来获取图像,直接插入url。
  • 处理错误响应,以便如果 gravatar 不存在(而不是其默认的 gravatar 图标)执行其他操作。

标签: javascript jquery angularjs gravatar


【解决方案1】:

我设法通过使用 FileReader API 和 XMLHttpRequest 解决了这类问题

var hashEmail = md5.createHash(email);

toImageUri('https://www.gravatar.com/avatar/' + hashEmail + '?d=404', function(imgDataUri){
             $('.result').html('<img src="' + imgDataUri + '" class="img-circle"/>'); 
    });

    function toImageUri(url, callback){
       var xhr = new XMLHttpRequest();
           xhr.responseType = 'blob';
           xhr.onload = function() {
               var reader  = new FileReader();
               reader.onloadend = function () {
               callback(reader.result);
           }
              reader.readAsDataURL(xhr.response);
          };
            xhr.open('GET', url);
            xhr.send();
    }

如果您真的需要纯 jQuery 解决方案,请查看此链接 https://github.com/acigna/jquery-ajax-native

【讨论】:

    猜你喜欢
    • 2018-10-15
    • 2015-02-26
    • 2017-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-02
    • 2013-10-14
    相关资源
    最近更新 更多