如何使用 xmlhttprequest 从 javascript 将字符串发送到 servlet

客户端代码:

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 中得到一个空值,在第二个中得到一个空白字符串.请有人帮忙.

Problem here is i am getting a null value in first System.out.println and a blank string in second one. Please somebody help.

推荐答案

客户端代码:

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

后面的字符串会

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

在 url 中添加参数

append your parameter in url

在服务器端

服务器代码:

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

使用stringParameter名称访问参数

相关文章