javascript 从ajax响应设置图像内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20468954/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 18:33:58  来源:igfitidea点击:

Set image content from ajax response

javascriptjqueryajaximagebase64

提问by Ashwin

I am making a ajax request in jquery as below. This ajax request gets images dynamically. And the image is always different image depending on the value of num

我正在 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 + '");
          }
    }
});

Is there a way to set image content using the response of the ajax request. Thanks.

有没有办法使用ajax请求的响应来设置图像内容。谢谢。

回答by Halcyon

You have some unneeded single quotes there. Use this:

你有一些不需要的单引号。用这个:

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

回答by Sridhar R

Try this

试试这个

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

You need to send the image back base64 encoded, look at this: http://php.net/manual/en/function.base64-encode.php

您需要将图像发送回 base64 编码,看这个:http: //php.net/manual/en/function.base64-encode.php

回答by Petra

I rarely use jquery but this worked for me: $(".avatar").html('<img src="' + user.avatar_url + '" />');Here i am adding an image to a class and avatar_url comes from the response from the server.

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