开发者

Newbie AJAX Qn: request.send(information)

I am completely new to AJAX hence this question. I want to send some information from my javascript code to my servlet.

function getDetails() {
    vals = document.getElementById("name").value;//works: vals does get inputted value
    request = createRequest();
    if (request == null) {
      alert("Unable to create request");
      return;
    }
    var url= "ValidateUser.do";
    request.open("POST", url, true);
    request.onreadystatechange = displayDetails;
    //How do I send the value of "vals" to my servlet?
    request.send("name="+vals);
}

When I run req.getParameter("name") on my servlet, I always get no value even though "vals" does contain the inputted value. So my question is- how do I access this value from my servlet?

EDIT:

function createRequest() {
  try {
    request = new XMLHttpRequest();
  } catch (tryMS) {
    try {
      request = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (otherMS) {
      try {
        request = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (failed) {
        request = n开发者_Python百科ull;
      }
    }
  }
  return request;
}

FURTHER EDIT: Servlet code: I want the println statement to print out the name.

//shortened: this method is called by a ControllerServlet
public Object perform(HttpServletRequest req, HttpServletResponse resp) {
    //retrieve customer from database
    model = SeekerCustomer.getCustomer(req.getParameter("name"));
    System.out.println(req.getParameter("name"));
}


 function ajaxRequest(){
  var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"] //activeX versions to check for in IE
  if (window.ActiveXObject){ //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken)
   for (var i=0; i<activexmodes.length; i++){
    try{
     return new ActiveXObject(activexmodes[i])
    }
    catch(e){
     //suppress error
    }
   }
  }
  else if (window.XMLHttpRequest) // if Mozilla, Safari etc
   return new XMLHttpRequest()
  else
   return false
 }

 function postReq(){
 var mypostrequest=new ajaxRequest()
 mypostrequest.onreadystatechange=function(){
  if (mypostrequest.readyState==4){
   if (mypostrequest.status==200 || window.location.href.indexOf("http")==-1){
    document.getElementById("my_Result_tag").innerHTML=mypostrequest.responseText //this is where the results will be put!
   }
   else{
    alert("An error has occured making the request")
   }
  }
 }
 var vals = document.getElementById("name").value
 var parameters="name="+vals
 mypostrequest.open("POST", "ValidateUser.do", true)
 mypostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
 mypostrequest.send(parameters)
 }

In the servlet access vals using:

 request.getParameter("name");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜