简体   繁体   English

Servlet对Javascript的响应以纯文本形式显示在浏览器上

[英]Servlet Response to Javascript in plain text shown on browser

I have my servlet sending the following response to a JS ajax call: 我让我的servlet向JS ajax调用发送以下响应:

            response.setContentType("text/plain");
            PrintWriter out = response.getWriter();
            out.print("start");
            out.close();

and the call from the web page has the following code: 并且来自网页的呼叫具有以下代码:

function update() {
    var xmlhttp = new XMLHttpRequest();
    var id = '${user.id}';
    var height = (window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight);
    height = height-40;
    var params = "action=update&id=" + id + "&height=" + height;
    xmlhttp.open("POST", "/Anabasis/UserControl", true);
    xmlhttp.setRequestHeader("Content-type",
            "application/x-www-form-urlencoded");
    xmlhttp.setRequestHeader("Content-length", params.length);
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            var answer = xmlhttp.responseText;
            if(answer=="start"){
                window.location.href = "/project/page1.jsp";
            } else {
                window.location.href = "/project/page2.jsp";
            }
        }
    };
    xmlhttp.send(params);
}
setTimeout(update, 10000);

If start is send back by the Servlet, the browser should be redirected to another page. 如果启动是由Servlet发送回的,则应将浏览器重定向到另一个页面。 This may be done without the user's doing anything since the JS request is send every 10 seconds. 由于JS请求每10秒发送一次,因此无需用户执行任何操作即可完成此操作。

Now the result is that I do not get the answer to page but just a black page with the text: "start" 现在的结果是我没有得到页面的答案,而只有一个带有文本的黑页:“开始”

Can anyone tell me what to add in order to asure that the answer gets back to the JS function? 谁能告诉我要添加什么以确保答案返回到JS函数?

It's better to forward your request according to your requirement, like: 最好根据您的要求forward您的请求,例如:

RequestDispatcher rd=request.getRequestDispatcher("./project/page1.jsp");
rd.forward(request, response);

I have found the solution, sorry for the question. 我已经找到了解决方案,对于这个问题感到抱歉。 The code actually works fine, just in some case the Servlet gets not called by this update function but by another form from the same page. 该代码实际上运行良好,只是在某些情况下,该更新函数未调用Servlet,而是从同一页面调用了另一种形式。 So of course the answer is not send to the function, explaining the misbehaviour. 因此,答案当然不会发送给函数,以解释错误行为。

Is there any guide on best practices concerning Servlet-Webpage communication? 是否有关于Servlet与网页通信的最佳实践的指南? I guess I shall need that very much. 我想我非常需要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM