如何从服务器端的XMLHttpRequest请求中接收所有参数?

问题描述:

我正在使用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); 
} 

你被错误编码形式的数据,你必须&,而不是由,到单独的字段。 对于概览请参见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