2011-08-01 33 views
0

我完全不熟悉AJAX因此這個問題。我想從我的JavaScript代碼發送一些信息到我的servlet。新手AJAX Qn:request.send(信息)

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

當我在我的servlet運行req.getParameter(「名稱」),我總是得到即使「丘壑」不包含輸入值沒有價值。所以我的問題是 - 我如何從我的servlet訪問這個值?

編輯:

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

進一步編輯: servlet代碼:我想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")); 
} 
+0

你能還添加源代碼的方法 '的createRequest()'? – reporter

回答

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

在servlet訪問丘壑使用:

request.getParameter("name"); 
+0

謝謝,但我如何訪問我的servlet頁面中的「參數」? – OckhamsRazor

+0

我編輯答案 –

+0

當我做System.out.println(request.getParamenter(「name」))時它仍然顯示爲null; – OckhamsRazor