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

标签 java javascript json servlets xmlhttprequest

客户端代码:

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

最佳答案

客户端代码:

 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中添加你的参数

在服务器端

服务器代码:

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

使用stringParameter名称访问参数

关于java - 如何使用 xmlhttprequest 从 javascript 将字符串发送到 servlet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15355435/

相关文章:

java - 麦克埃利切(FlexiProvider): How can i create KeyPair from byte array?

javascript - 将 mySQL 日期转换为 Javascript 日期

javascript - react : Return Statement

javascript - 在特定时间(秒)后调用 js url

java - 优化 ArrayList.removeAll

Java Date 对象解析精度在 SimpleDateFormat 上关闭

JavaFX 编译警告 - "uses unchecked or unsafe operations"- 原始数据类型?

json - swift 4 : Keeping the same order when parsing a JSON

javascript - 用于 jQuery UI 自动完成的 JSON 数组

javascript - 如何从 Spark 获取数据并使用 Angular 显示