How to display an image that we received through Ajax call?

一世执手 提交于 2021-02-07 05:52:26

问题


Web server generates images and sends them to client directly. There are no URLs to the images, for security reasons. For example, if I enter /images/25 URL in the browser server will send it and browser will download it.

Now I want to get this image from Ajax call and then display it on existing page. I can get the image data. My question is: how can I display an image?

$.get("/images/25", function (rawImageData) {
   // ??? Need to add an image to DOM
});

Update

I apologize for being so stupid. Thank you, JW. Of course I can just put img tag with src to my URL. It does not matter if this is a direct URL to an image file or the server sends it dynamically.


回答1:


So it sounds like there is a URL, and it's /images/25.

As far as I know, you can't display image data that you get from an AJAX call*. But why not just put the URL in an <img> tag? It doesn't matter to the browser that the image is generated by the server, rather than read from a file.

*EDIT: I was wrong; see gideon's answer if you really need to use an AJAX call (e.g. you need to make a POST request, or send certain headers).




回答2:


To expand on Matt's answer you could use base64 encoded img urls. This is an example from wikipedia of what that img tag would look like:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA
 AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
 9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />

You need a blank image:

<img id="target" src="" />

Your server needs to return the image as a base64 string, then you could do:

$.get("/images/25", function (rawImageData) {
      $("#target").attr("src","data:image/gif;base64," + rawImageData);
});

See this MDN reference for more in base64 encoded img urls.

I made a short demo here: http://jsfiddle.net/99jAX/1/




回答3:


You want to send the raw image data base64-encoded, combined with the data:// URI scheme.




回答4:


I'd bank on it being the same as if you rendered if via PHP or ASP or whatever. just something simple like

$('#elementOfChoice').append('<img src="'+ rawImageData +'" alt="something" />');

though I could be wrong. All depends on whats happening behind the scenes to make that image become what it is. If its gotta pass through a PHP file cause its a base_64 image and needs to be encoded, or whatever the case then that has to be done accordingly.




回答5:


$( "<img>" ).attr( "src", icon_url ).appendTo( "#images" );


来源:https://stackoverflow.com/questions/9511302/how-to-display-an-image-that-we-received-through-ajax-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!