Новичок AJAX Qn: request.send (информация) - PullRequest
0 голосов
/ 01 августа 2011

Я совершенно новичок в AJAX, поэтому этот вопрос. Я хочу отправить некоторую информацию из моего кода JavaScript в мой сервлет.

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);
}

Когда я запускаю req.getParameter ("name") на своем сервлете, я всегда не получаю значения, даже если "vals" действительно содержит введенное значение. Поэтому мой вопрос - как мне получить доступ к этому значению из моего сервлета?

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 = null;
      }
    }
  }
  return request;
}

ДОПОЛНИТЕЛЬНОЕ РЕДАКТИРОВАНИЕ: Код сервлета: я хочу, чтобы оператор println выводил имя.

//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"));
}

1 Ответ

1 голос
/ 01 августа 2011
 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)
 }

В значениях доступа сервлета:

 request.getParameter("name");
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...