将数据从JSP发送到servlet

Send data from JSP to servlet

本文关键字:servlet JSP 数据      更新时间:2023-09-26

以下是我的需求:

在jsp中,我使用javascript填充"表"(我的第一个"tr"是标题,第二个"tr"是输入,然后所有新的"tr"都添加了javascript函数)

现在我想将表的值发送给servlet。不使用jquery框架

这是我在js中所做的:

function test(){
    var strPar= "Blabla BLABLA BLA";
    var toServer = JSONObject.toJSONString(strPar);
    alert("TEST U MF !!!");
    var request = new XMLHttpRequest();
    request.open("POST", "http://localhost:8084/Calendar/Legal", true);
    request.send(toServer);
    alert("POUET !");
}

我似乎根本不起作用!此外,我不知道如何从servlet获得JSON对象?

public class LegalCalServlet extends HttpServlet {
/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    System.out.println("TEST ");
    String output = request.getParameter("strPar");
    System.out.println(output);
}}

我将非常感谢任何帮助,请!

使用说明:

 xmlhttp.open("POST","demo_post2.asp",true);
 xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
 xmlhttp.send("fname=Henry&lname=Ford");

您可以在此网站查看示例和教程:http://www.w3schools.com/ajax/ajax_xmlhttprequestrongend.asp

var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
   xmlhttp=new XMLHttpRequest();
   }
 else
   {// code for IE6, IE5
   xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
   }
 xmlhttp.onreadystatechange=function()
   {
   if (xmlhttp.readyState==4 && xmlhttp.status==200)
     {
     document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
     }
   }
 xmlhttp.open("POST","demo_post2.asp",true);
 xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
 xmlhttp.send("fname=Henry&lname=Ford");
 }

尝试在请求中添加标头-

下面是一个从http://www.openjs.com/articles/ajax_xmlhttp_using_post.php

发送数据的示例
var url = "get_data.php";
var params = "lorem=ipsum&name=binny";
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
    if(http.readyState == 4 && http.status == 200) {
        alert(http.responseText);
    }
}
http.send(params);