处理XMLHttpRequest中的图像(使用HTML和Javascript) [英] Handling images from XMLHttpRequest (with HTML and Javascript)

查看:636
本文介绍了处理XMLHttpRequest中的图像(使用HTML和Javascript)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用XMLHttpRequest从服务器获取图像(从第三方服务器小程序本地运行)

I am using an XMLHttpRequest to fetch an image from a server (run locally from a third party server-applet)

简化版本的代码如下所示。

A simplified version of the code is shown below.

图像作为JPEG返回,返回的标题显示content-type = image / jpg。我可以通过Firebug for Firefox查看信息。

The image is returned as a JPEG and the returned header shows "content-type= image/jpg". I can view the information via Firebug for Firefox.

然而,我有一个可怕的时间能够在网页上显示实际的图像,因为它是从服务器返回的图像数据而不是图像位置的uri 。

However I am having a terrible time being able to show the actual image on a webpage because it is the image data being returned from the server NOT a uri to the image location.

从返回的数据中显示此图像的正确方法是什么?我应该使用< span> 标签或< img> 标签或< magical-show-image-from-data> 标签?

What is the proper way to display this image from the returned data? Should I be using a <span> tag or an <img> tag or a <magical-show-image-from-data> tag?

function getXML(url, postData, requestStateChangeHandler){        
    if(window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {//Code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = requestStateChangeHandler;

    xmlhttp.open("POST", url, true);
    xmlhttp.setRequestHeader('Content-Type', 'text/xml');
    xmlhttp.setRequestHeader('Cache-Control', 'no-cache');
    xmlhttp.send(postData);
}


function requestStateChangeHandler(){
    if (xmlhttp.readyState == 4) 
    {
        if(xmlhttp.status == 200)
        {
            document.getElementById('results').innerHTML = xmlhttp.responseText;
        }
        else
            dump("Error loading page\n");
    }
}


推荐答案

你可以使用内联图像

在服务器端编码您在base64中的响应

on server side encode your response in base64

在php中使用 base64_encode(你的数据)

和javascript

in php use base64_encode("your data")
and in javascript

result = document.getElementById('results');
result.innerHTML = '<img src="data:image/gif;base64,' + xmlhttp.responseText + '"/>';

这篇关于处理XMLHttpRequest中的图像(使用HTML和Javascript)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆