无法通过异步ajax调用呈现base64图像返回

Failing to render base64 image return by async ajax call

本文关键字:base64 图像 返回 调用 ajax 异步      更新时间:2023-09-26

我尝试进行多个异步ajax调用,其中一个是从服务器请求base 64图像。如果我将base64图像的ajax请求设置为同步,它适用于IE, Chrome和Firefox。然而,对于异步的情况,图像在IE中每次都被渲染,而不是在Chrome和Firefox中偶尔渲染。有时它被渲染,有时没有。最重要的是,移动浏览器根本不渲染图像。

代码很简单,但我不知道哪里出了问题。

function TestViewModel() {
  var self = this;
  
  self.Image = ko.observable();
 
  
  self.GetProfileData = function () {
    $.ajax({
     async: true,
     type: 'GET',
     url: ..,
     success: {
        // return profile data
     }  
    });
  }
  
  self.GetProfileImage = function() {
    $.ajax({
       async: true, 
       type: 'GET',
       url: ..,
       success(data): {
        self.Image(data.Base64Image);
       }
    });
   }
  
  self.GetProfileData();
  self.GetProfileImage();
}
ko.applyBindings(new TestViewModel());
<img data-bind="attr: { src: Image }" alt="ProfileImage" />

我想你应该使用内容类型前缀:

self.Image("data:image/x;base64," + data.Base64Image);