从ajax响应设置图像内容

Set image content from ajax response

本文关键字:图像 设置 ajax 响应      更新时间:2024-05-06

我在jquery中发出一个ajax请求,如下所示。这个ajax请求动态获取图像。根据num 的值,图像总是不同的图像

$.ajax({
    type: "POST",
    url: "ABC.php?num=1",
    success: function(response) {
          if(response == 1) {
                //some code
          }
          else {
                // Here I am not able to set image content.
                $("#image").attr("src", "data:image/png;base64,' + response + '");
          }
    }
});

有没有一种方法可以使用ajax请求的响应来设置图像内容。谢谢

您有一些不需要的单引号。使用此:

$("#image").attr("src", "data:image/png;base64," + response);

试试这个

$('#image').html('<img src="data:image/png;base64,' + response + '" />');

您需要将图像发送回base64编码,请查看以下内容:http://php.net/manual/en/function.base64-encode.php

我很少使用jquery,但这对我很有用:$(".avatar").html('<img src="' + user.avatar_url + '" />');在这里,我将一个图像添加到一个类中,avatar_url来自服务器的响应。