如何将JavaScript变量传递到Java Servlet DoPost中

时间:2018-12-04 07:43:49

标签: javascript java jquery servlets

我有一个HTML表,如果用户单击任何下拉菜单,我正在做的就是下拉列表,我现在将列名和对应的行(billdate)存储到变量中,要做的就是将此变量传递到我的java servelt doPost方法中,并使用该变量进入doGet进行另一个ajax调用。 我已经搜索了很多将变量从javascript传递到Java servlet的方法,但是没有任何好的答案。

这是我的javascript表代码

<div id="tbl"></div>

<ul id="contextMenu" class="dropdown-menu" role="menu">
  <li><a href="#" class="link1">Report1</a></li>
  <li><a href="#" class="Link2">Report2</a></li>
</ul>
    var currentlyClickedPlace = "";
$(window).load(function() {
  $dropdown = $("#contextMenu");
  $(".actionButton").click(function() {
    //move dropdown menu
    $(this).after($dropdown);
    //update links
    $(this).dropdown();

    currentlyClickedOutlet = $(this).attr("data-place");
    currentlyClickedBilldate = $(this).attr("data-plac");
  });
  $(".link1").click(function(){

    console.log(currentlyClickedOutlet)
    console.log(currentlyClickedBilldate)
 //   here  i have to make two ajax call one to send currentlyClickedOutlet and currentlyClickedBilldate to the server i.e javaservlet doPost
  //  and another one to bind new html table into test div wchich will give me data based on clicked dropdown
    //call ajax and bind the data into test div
  });

});

data = [{
    "amount": 291589,
    "billdate": "2018-08-01",
    "outlet": "JAYANAGAR"
  },
  {
    "amount": 58337,
    "billdate": "2018-08-01",
    "outlet": "MALLESHWARAM"
  },
  {
    "amount": 65970,
    "billdate": "2018-08-01",
    "outlet": "KOLAR"
  },
  {
    "amount": 296125,
    "billdate": "2018-08-02",
    "outlet": "JAYANAGAR"
  },
  {
    "amount": 56545,
    "billdate": "2018-08-02",
    "outlet": "MALLESHWARAM"
  },
  {
    "amount": 72213,
    "billdate": "2018-08-02",
    "outlet": "KOLAR"
  },
  {
    "amount": 346605,
    "billdate": "2018-08-03",
    "outlet": "JAYANAGAR"
  },
  {
    "amount": 62459,
    "billdate": "2018-08-03",
    "outlet": "MALLESHWARAM"
  },
  {
    "amount": 65248,
    "billdate": "2018-08-03",
    "outlet": "KOLAR"
  },
  {
    "amount": 518212,
    "billdate": "2018-08-04",
    "outlet": "JAYANAGAR"
  },
  {
    "amount": 104801,
    "billdate": "2018-08-04",
    "outlet": "MALLESHWARAM"
  },
  {
    "amount": 138151,
    "billdate": "2018-08-04",
    "outlet": "KOLAR"
  },
  {
    "amount": 628358,
    "billdate": "2018-08-05",
    "outlet": "JAYANAGAR"
  },
  {
    "amount": 115223,
    "billdate": "2018-08-05",
    "outlet": "MALLESHWARAM"
  },
  {
    "amount": 134107,
    "billdate": "2018-08-05",
    "outlet": "KOLAR"
  },
  {
    "amount": 177866,
    "billdate": "2018-08-06",
    "outlet": "JAYANAGAR"
  },
  {
    "amount": 66095,
    "billdate": "2018-08-06",
    "outlet": "KOLAR"
  },
  {
    "amount": 284069,
    "billdate": "2018-08-07",
    "outlet": "JAYANAGAR"
  },
  {
    "amount": 58789,
    "billdate": "2018-08-07",
    "outlet": "MALLESHWARAM"
  },
  {
    "amount": 67886,
    "billdate": "2018-08-07",
    "outlet": "KOLAR"
  },
  {
    "amount": 313128,
    "billdate": "2018-08-08",
    "outlet": "JAYANAGAR"
  },
  {
    "amount": 59939,
    "billdate": "2018-08-08",
    "outlet": "MALLESHWARAM"
  },
  {
    "amount": 68558,
    "billdate": "2018-08-08",
    "outlet": "KOLAR"
  }
]

let formatData = function(data) {

  let billdates = [];
  let outlets = [];
  data.forEach(element => {
    if (billdates.indexOf(element.billdate) == -1) {
      billdates.push(element.billdate);
    }
    if (outlets.indexOf(element.outlet) == -1) {
      outlets.push(element.outlet);
    }
  });
  return {
    data: data,
    billdates: billdates,
    outlets: outlets,

  };
};



let renderTable = function(data, divId, filterdata) {
  billdates = data.billdates;
  outlets = data.outlets;
  data = data.data;
  let tbl = document.getElementById(divId);
  let table = document.createElement("table");
  let thead = document.createElement("thead");
  let headerRow = document.createElement("tr");
  let th = document.createElement("th");
  th.innerHTML = "Bill___Date";
  th.classList.add("text-center");
  headerRow.appendChild(th);
  let grandTotal = 0;
  let outletWiseTotal = {};
  th = document.createElement("th");
  th.innerHTML = "Total1";
  th.classList.add("text-center");
  headerRow.appendChild(th);

  outlets.forEach(element => {
    th = document.createElement("th");
    th.innerHTML = element;
    th.classList.add("text-center");
    headerRow.appendChild(th);
    outletWiseTotal[element] = 0;
    data.forEach(el => {
      if (el.outlet == element) {
        outletWiseTotal[element] += parseInt(el.amount);
      }
    });
    grandTotal += outletWiseTotal[element];
  });


  thead.appendChild(headerRow);
  headerRow = document.createElement("tr");
  th = document.createElement("th");
  th.innerHTML = "Total";
  th.classList.add("text-center");

  headerRow.appendChild(th);

  outlets.forEach(element => {
    th = document.createElement("th");
    th.innerHTML = outletWiseTotal[element];
    th.classList.add("text-right"); 
    headerRow.appendChild(th);
  });

  th = document.createElement("th");
  th.innerHTML = grandTotal;
  th.classList.add("text-right"); // grand total

  headerRow.insertBefore(th, headerRow.children[1]);
  thead.appendChild(headerRow);
  table.appendChild(thead);

  let tbody = document.createElement("tbody");

  billdates.forEach(element => {
    let row = document.createElement("tr");
    td = document.createElement("td");
    td.innerHTML = element;
    row.appendChild(td);
    let total = 0;

    outlets.forEach(outlet => {
      let el = 0;
      data.forEach(d => {
        if (d.billdate == element && d.outlet == outlet) {
          total += parseInt(d.amount);
          el = d.amount;
        }
      });




      td = document.createElement("td");
      a = document.createElement("a");

      td.classList.add("text-right");
      td.classList.add("dropdown");
      a.classList.add("btn");
      a.classList.add("btn-default");
      a.classList.add("actionButton");

      a.setAttribute("data-place", outlet);
      a.setAttribute("data-plac", element);



      a.setAttribute("data-toggle", "dropdown");
      a.innerHTML = el;
      td.appendChild(a); 

      row.appendChild(td);




    });


    td = document.createElement("td");
    td.innerHTML = total;
    td.classList.add("text-right"); 

    row.insertBefore(td, row.children[1]);
    tbody.appendChild(row);

  });

  table.appendChild(tbody);

  tbl.innerHTML = "";
  tbl.appendChild(table);
  table.classList.add("table");
  table.classList.add("table-striped");
  table.classList.add("table-bordered");
  table.classList.add("table-hover");
}
let formatedData = formatData(data);
renderTable(formatedData, 'tbl', '');

因此,当生病时将值单击到我的dopost方法中时,我必须在我的doGet中使用该变量来进行另一个ajax调用,以向test div

中显示一些新数据

我知道如何在servlet中声明全局属性以在应用程序中的任何地方使用该变量

getServletContext().setAttribute("DateAttribute", Date);

这是我的javaservlet代码

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {


    String Date=getServletContext().getAttribute("DateAttribute").toString(); // this how i will access Date and Outlet from dopost to doget
    String Outlet=getServletContext().getAttribute("OutletAttribute").toString();

    //will use here the value of Date and Outlet


    response.getWriter().append("Served at: ").append(request.getContextPath());
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String Date = request.getParameter("currentlyClickedBilldate");  //here i want that values from java script
    String Outlet = request.getParameter("currentlyClickedOutlet");  //here i want that values from java script


    getServletContext().setAttribute("DateAttribute", Date);  //this is how i will make Date and Outlet a global variables to access anywhere in my application
    getServletContext().setAttribute("OutletAttribute", Outlet);

    doGet(request, response);
}
  • 我只想知道如何通过ajax将变量从Java脚本传递到Java servlet,请帮帮我

这是我的HTML表格的小提琴

fiddle

我必须进行两个Ajax调用,一个是将数据发布到servlet中,另一个是从servlet中获取数据以将新表呈现到test div中,而这两个调用将在下拉菜单上单击,即{{1}首先我想发布数据,然后通过ajax从do调用该数据后 请任何人在这里帮助我

1 个答案:

答案 0 :(得分:0)

您在下面检查以了解如何使用AJAXservlet发送数据

您可以使用data将数据发送到servlet,也可以使用?使用查询参数。请参见以下示例。

Jquery-ajax-options

请注意,http://localhost:8080/testpost取决于您的应用程序。

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("#id1").click(function(){
        var user = 'get-user-by-query-param';
        $.get("http://localhost:8080/testget?name="+user, function(data, status){
            alert("Data: " + data + "\nStatus: " + status);
            $("#divId1").html(data);
        });
    });

    $("#id2").click(function(){
        var user = 'post-user-by-query-param';
        $.post("http://localhost:8080/testpost?name="+user, function(data, status){
            alert("Data: " + data + "\nStatus: " + status);
            $("#divId2").html(data);
        });
    });


    $("#id3").click(function(){

        var user = 'get-user-by-sending-in-data';
        var data = {"name": user};
        $.get("http://localhost:8080/testget",data, function(data, status){
            alert("Data: " + data + "\nStatus: " + status);
            $("#divId3").html(data);
        });
    });


    $("#id4").click(function(){
        var user = 'post-user-by-sending-in-data';
        var data = {"name": user};
        $.post("http://localhost:8080/testpost",data, function(data, status){
            alert("Data: " + data + "\nStatus: " + status);
            $("#divId4").html(data);
        });
    });

      $("#id5").click(function(){
        var user = 'get-user-by-query-param';
        $.get("http://localhost:8080/testget?name="+user, function(data, status){
            alert("Data: " + data + "\nStatus: " + status);
            $("#divId1").html(data);
            var postData = {'name':data}
            $.post("http://localhost:8080/testpost",postData, function(data, status){
            alert("Data: " + data + "\nStatus: " + status);
            data
            $("#divId4").html(data);
        });
        });
    });
});
</script>
</head>
<body>

<button id="id1">GET with query param</button>
<div id="divId1"></div>
<button id="id2">POST with query param</button>
<div id="divId2"></div>
<button id="id3">GET with data</button>
<div id="divId3"></div>
<button id="id4">POST with data</button>
<div id="divId4"></div>

<button id="id5">POST and GET with data</button>
<div id="divId5"></div>

</body>
</html>

我觉得最好用这些来链接电话。

https://api.jquery.com/promise/

使用诺言链接电话:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){

      $("#id5").click(function(){
        var user = 'get-user-by-query-param';
        $.when( $.get( "http://localhost:8080/testget?name="+user ) ).done(function( data, textStatus, jqXHR ) {
            $("#divId5").html(data);
            var postData = {'name':data+' second input'}
            $.post("http://localhost:8080/testpost",postData, function(data, status){
            alert("Data: " + data + "\nStatus: " + status);

            $("#divId5").append("<br/>"+data);
        });
});

    });
});
</script>
</head>
<body>



<button id="id5">POST and GET with data</button>
<div id="divId5"></div>

</body>
</html>

以下是我使用springMVC

的控制器类
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class WelcomeController {



    @RequestMapping("/testpost" )
    @PostMapping
    @ResponseBody
    public String testPost(HttpServletRequest request, HttpServletResponse response) {
        String name = request.getParameter("name");
        return name;
        //return "welcome"; //if you want to return jsp
    }

    @RequestMapping("/testget" )
    @PostMapping
    @ResponseBody
    public String testGet(HttpServletRequest request, HttpServletResponse response) {
        String name = request.getParameter("name");
        return name;
        ///return "welcome";
    }

}