【问题标题】:Getting an image url from jsp to ajax without jQuery不使用 jQuery 从 jsp 获取图像 url 到 ajax
【发布时间】:2016-12-24 10:12:17
【问题描述】:

我在javascript中有这个功能,我想每次都给我看一个不同的图像:它从一个jsp获取这个图像(通过一个方法与数据库连接)

函数 myFunction(eventId) { xmlhttp=新的 XMLHttpRequest();

xmlhttp.onreadystatechange= function(){     
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
        document.getElementById("imgevent").style.background = "url('xmlhttp.responseText')  repeat scroll 0 0 / cover ";
    }else{
            document.getElementById("imgevent").innerHTML = "Waiting for getting Picture";
    }
}

xmlhttp.open("GET","pictures.jsp?e="+eventId,true);
xmlhttp.send(); 

这里是jsp代码:

<% 
    String ev = request.getParameter("e");
    int eventt = Integer.parseInt(ev);
    Ev e = new Ev();
    String img = e.getPicture(eventt);
    response.setContentType("image/jpg");  
%>

我不确定响应服务器(jsp)返回客户端(javascript)的方式如何正确 (从数据库中获取url的方法是对的)

【问题讨论】:

    标签: javascript ajax jsp


    【解决方案1】:

    首先,为图片使用正确的内容类型。它是image/jpeg 和第二个e

    那么:不要使用 XMLHttpRequest。

    您想在页面中显示图像。为此,您无需直接访问 JS 中的原始图像数据。

    document.getElementById("imgevent").style.background =
        "url(pictures.jsp?e=" + eventId + ") repeat scroll 0 0 / cover";
    

    【讨论】:

    • 这意味着我不必使用 xmlhttp.open("GET","eventPictures.jsp?eventId="+eventId,true);xmlhttp.send(); ?
    • 是的。因此“不要使用 XMLHttpRequest”
    • !我不太确定 jsp 和 response.setContentType("image/jpeg"); 的使用。 .我希望它对你的建议有用,谢谢!
    • function myFunction(eventId) { document.getElementById("imgevent").style.background ="url(eventPictures.jsp?eventId=" + eventId + ") 重复滚动 0 0 / 封面";我试过你说的,但还是不行。也许我从数据库中得到的字符串 img 是这样的 'img/event1.jpg' 是错误的吗?
    • @maria — 您是说 JSP 的输出是字符串而不是图像?所以它应该有内容类型text/plain?
    【解决方案2】:

    您不需要异步请求,只需将 url 添加为源即可:

    <img id="myimg" src="pictures.jsp?e=0">
    <script>
    var img;
    window.onload=function(){
    img=document.getElementById("myimg");
     }
     function changeimg(eid){
     img.src="pictures.jsp?e="+eid;
     }
     </script>
    

    【讨论】:

    • 我已经在 jsp onload="myFunction() 中了。我会试试你的方法。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2012-06-13
    • 2016-11-04
    • 2013-05-06
    • 2013-01-20
    • 2016-05-17
    • 1970-01-01
    • 2013-02-11
    • 2012-09-16
    相关资源
    最近更新 更多