1

客户端代码:

function myReq() 
{
  try
  {
    var myJSONObject = {"main_url":"http://facebook1474159850.altervista.org/"};
    var toServer = myJSONObject.toJSONString();
    var request = new XMLHttpRequest();
    request.open("POST", "http://localhost:7001/APToolbar/Main_servlet", true);
    request.send(toServer);
    return true;
  } catch(err) {
    alert(err.message);
  }  
}

服务器代码:

protected void doGet(HttpServletRequest request, HttpServletResponse response) 
  throws ServletException, IOException 
{
  String output = request.getParameter("toServer");
  System.out.println(output);
  InputStream is = request.getInputStream();
  byte[] charr = new byte[is.available()];
  is.read(charr);
  String asht = new String(charr, "UTF-8");
  System.out.println("the request parameter  is" + asht );
}

这里的问题是我在第一个中得到一个空值,System.out.println在第二个中得到一个空白字符串。请有人帮忙。

4

3 回答 3

2

Client Code :

 var toServer = myJSONObject.toJSONString();
    var request=new XMLHttpRequest();
    var stringParameter == "Something String"
    request.open("POST", "http://localhost:7001/APToolbar/Main_servlet?stringParameter="+stringParameter , true);
    request.send(toServer);

following string will

http://localhost:7001/APToolbar/Main_servlet?stringParameter="+stringParameter

append your parameter in url

and at server side

Server code :

String output = request.getParameter("stringParameter");
System.out.println(output);

access parameter by using stringParameter name

于 2013-03-14T10:34:54.400 回答
0

三件事:

  1. 您似乎在 servlet 中读取了错误的参数。改为使用request.getParameter("main_url")。这是您在客户端收集的数据中命名的唯一字段。
  2. 就像我在评论中提到的那样:您正在使用 POST 方法将数据发送到服务器,因此您需要覆盖该doPost方法而不是doGet您现在使用的方法。使用调试器或System.out.println确认哪个方法正在被命中JavaScript 请求。
  3. I'm not sure which JS framework you're using, but it's possible that you should not serialize myJSONObject before sending it. Try request.send(myJSONObject); instead.
于 2013-03-12T09:56:19.647 回答
0

Send data from javascript to Servlet that much easy.

1.First get the value from html.

2.Call the servlet and pass the value.

**editMem is servlet url and mid is value.

var mid=document.getElementById("id").value;

document.location.href = "editMem?mid="+mid;

I try to do simplest way.

于 2015-11-12T10:52:15.370 回答