java 如何使用jsp将响应返回给AJAX?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17216927/
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-11-01 01:19:51  来源:igfitidea点击:

How to return response to AJAX using jsp?

javahtmlajaxjspdojo

提问by ricardo28

I'm new to jsp, so I'd like to know how to return a response to AJAX. This is the code to submit the form using dojo with AJAX:

我是 jsp 的新手,所以我想知道如何向 AJAX 返回响应。这是使用带有 AJAX 的 dojo 提交表单的代码:

<script type="text/javascript">
        dojo.require("dojo.io.iframe");

        dojo.addOnLoad(function() {
            upload = function(  ) {
            dojo.io.iframe.send({
                form : "fileUploader",
                handleAs : "html", //response type from the server
                url : "url to jsp",//just example, not the real url
                load : function(response, ioArgs) {
                    console.log(response, ioArgs);
                    return response;
                },
                error : function(response, ioArgs) {
                    console.log("error");
                    console.log(response, ioArgs);
                    return response;
                }
            });
        };
        });

and this is the fragment of the jsp code to return the response:

这是返回响应的jsp代码片段:

r = "<p >You have successfully uploaded your video. </p>";
response.setContentType("text/html");
response.getWriter().write(r);

if I just use System.out.println(r), it does print the result in console, so the form is being submitted. So I think the problem is the way I'm returning the response or the way I'm handling it with dojo.

如果我只使用 System.out.println(r),它会在控制台中打印结果,因此正在提交表单。所以我认为问题在于我返回响应的方式或我使用 dojo 处理它的方式。

Thanks in advance!

提前致谢!

回答by grepit

Here is simple AJAX and JSP ( no jquery) to click on a button and get a time back into a input box. look at the line " document.myForm.time.value=xmlhttp.responseText; " where it gets the response and set the result in the jsp.

这是简单的 AJAX 和 JSP(没有 jquery)来单击一个按钮并将时间返回到输入框中。查看“ document.myForm.time.value=xmlhttp.responseText; ”这一行,它获取响应并在jsp 中设置结果。

<html>
<head>
<title>JSP and Servlet using AJAX</title>
<script type="text/javascript">



function getXMLObject()  //XML OBJECT
{
   var xmlHttp = false;
   try {
     xmlHttp = new ActiveXObject("Msxml2.XMLHTTP")  // For Old Microsoft Browsers
   }
   catch (e) {
     try {
       xmlHttp = new ActiveXObject("Microsoft.XMLHTTP")  // For Microsoft IE 6.0+
     }
     catch (e2) {
       xmlHttp = false   // No Browser accepts the XMLHTTP Object then false
     }
   }
   if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
     xmlHttp = new XMLHttpRequest();        //For Mozilla, Opera Browsers
   }
   return xmlHttp;  // Mandatory Statement returning the ajax object created
}

var xmlhttp = new getXMLObject();   //xmlhttp holds the ajax object

function ajaxFunction() {
  var getdate = new Date();  //Used to prevent caching during ajax call
  if(xmlhttp) {

    xmlhttp.open("GET","ControlServlet?gettime=gettime" ,true);
    xmlhttp.onreadystatechange  = handleServerResponse;
    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlhttp.send(null);
  }
}

function handleServerResponse() {
   if (xmlhttp.readyState == 4) {
     if(xmlhttp.status == 200) {
       document.myForm.time.value=xmlhttp.responseText; //Update the HTML Form element 
     }
     else {
        alert("Error during AJAX call. Please try again");
     }
   }
}
</script>
</head>
<body>
<form name="myForm">
Server Time:<input type="text" name="time" />
<br />
<input type="button" onClick="ajaxFunction()" value="Click"/>
<br />
</form>
</body>
</head>
</html>

here is servlet for it:

这是它的servlet:

public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
        StringBuffer requestURL = request.getRequestURL();
        if (request.getQueryString() != null) {
            requestURL.append("?").append(request.getQueryString());
        }
        String completeURL = requestURL.toString();

        if(request.getParameter("gettime")!= null && !request.getParameter("gettime").toString().equals("")){ 
        PrintWriter out = response.getWriter();
        Date df = new Date();
        out.println(df.getTime());
        }
    }

    public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
        doPost(request,response);
    }
}

here is what you should see after running the above code: enter image description here

以下是运行上述代码后您应该看到的内容: 在此处输入图片说明