简体   繁体   中英

I can't get my servlet to send parameters to my jsp file using ajax and xml

This is my servlet code and there are no errors and it appears to be fine:

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(urlPatterns={"/AjaxServlet"})

public class AjaxServlet extends HttpServlet {

public AjaxServlet() {
    super();
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throwsm ServletException, IOException {}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    processRequest(request, response);
}

protected void processRequest(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
    response.setContentType("text/xml");        
    response.getWriter().println("<xmlResponse>" +request.getParameter("name")+ "</xmlResponse>");
}

}

and this is my javascript on my jsp page, this function is called from an 'onChange' event on my jsp page:

<script>         
function callAjaxServlet(){

var xmlhttp;
var opt = $("#populateGraveYardList option:selected").text();

if (window.XMLHttpRequest) {
    xmlhttp= new XMLHttpRequest();
}else if(window.ActiveXObject) {
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

sendMessage;

function sendMessage(){
    xmlhttp.open("POST", "AjaxServlet?name=" + opt ,true);
    xmlhttp.send();
    xmlhttp.onreadystatechange = receiveMessage;
}

function receiveMessage(){
    if(xmlhttp.readyState ===4 && xmlhttp.status===200){ 
    var opt1 = xmlhttp.responseXML.getElementByTagName("xmlResponse")[0].text;
    $("#gName").val(opt1);
    }
}
}
</script>

The servlet is receiving the parameters fine but not sending them back to my jsp page...what am I doing wrong please? Thanks in advance. (New to Ajax by the way, just trying to figure it out!) opt1 keeps coming up as undefined.

Have you considered using the ajax feature in jQuery?

   $.ajax({
       url: "jsp file here",
       type: "post",
       data: {"your name/value pairs here")
       success: function(response){
       },
       error:function(xhr, ajaxOptions, thrownError){
       }   
     });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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