2011-05-09 30 views
0

我正在使用XMLHttpRequest創建一個簡單的表單提交併傳遞2個參數。在服務器端,我正在接收這兩個參數,但如何讓它們處於不同的變量中?如何從服務器端的XMLHttpRequest請求中接收所有參數?

這裏是Servlet

PrintWriter out = response.getWriter(); 
    response.setContentType("text/plain"); 

    paramMap=request.getParameterMap(); 
    if (paramMap == null) 
     throw new ServletException(
      "getParameterMap returned null in: " + getClass().getName()); 

    iterator=paramMap.entrySet().iterator(); 
    System.out.println(paramMap.size()); 
    String str=""; 

    while(iterator.hasNext()) 
    { 
     Map.Entry me=(Map.Entry)iterator.next(); 
     String[] arr=(String[])me.getValue(); 
     configId=arr[0]; 
     System.out.println(me.getKey()+" > "+configId); 
    } 
/***Above println** i get "name > Abhishek,filename=a.txt*/ 

    rand=new Random(); 
    randomInt=rand.nextInt(1000000); 
    configId=randomInt+configId; 
    System.out.println(configId); 
    out.println(configId); 

    /*creates a new session if a session does not exist already*/ 

    session=request.getSession(); 
    session.setAttribute("cid", configId); 

    out.close(); 

/*I also need to check a session name `uid` i.e., already created before calling this servlet and then only get both the parameters in parameterMap and store all the params in session. so i'd like to do something like this */ 

session=request.getSession(false); 
if(session!=null) //then get all the parameters here and store them into session 
{ 
    uid=session.getAttribute("uid").toString(); 

    /*get nameFromTheParameterMap and fileNameFromTheParameterMap from paramt 
    session.setAttribute("name", nameFromTheParameterMap); 
    session.setAttribute("filename", fileNameFromTheParameterMap); 
} 

這是正確的做法?還有我怎麼會得到dataString參數parameterMap的

這裏是saveconfig的功能

function saveConfig() 
{ 
var url_action="/temp/SaveConfig"; 
var client; 
var dataString; 

if (window.XMLHttpRequest){ // IE7+, Firefox, Chrome, Opera, Safari 
    client=new XMLHttpRequest(); 
} else {     // IE6, IE5 
    client=new ActiveXObject("Microsoft.XMLHTTP"); 
} 

client.onreadystatechange=function(){ 

    if(client.readyState==4&&client.status==200) 
    { 
     alert(client.responseText); 

    } 
}; 

dataString="name="+document.getElementById("name").value+",filename="+document.getElementById("tfile").value; 
client.open("POST",url_action,true); 
client.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 

client.send(dataString); 
} 

回答

1

你被錯誤編碼形式的數據,你必須&,而不是由,到單獨的字段。 對於概覽請參見Wikipedia

這對於具有可能 重複鍵編碼鍵 - 值對的格式。每個鍵值對都是由&字符分隔的 ,並且 每個鍵都通過'='字符與其值 分開。

順便說一句,你的Java代碼看起來冗長,您可以通過使用的for-each-循環簡化。

+0

嘿,謝謝問題解決了,我忘記使用'multipart/form-data'也可以告訴我使用session的方法是正確的嗎? – abi1964 2011-05-09 07:38:44

+0

如何簡化在我的js中使用for循環?你指的是'dataString' var嗎? – abi1964 2011-05-09 07:41:09

相關問題