how to pass a javascript variable to a java servlet? [duplicate]

梦想与她 提交于 2019-12-31 07:18:13

问题


I want to pass a javascript variable to a java servlet. I am developing a web application. This is my html code:

<p id="test">Some text</p>

And this is what i write in the javascript file:

var myVar = document.getElementById('test').innerText;

$.ajax({
    url: 'Test',
    data: {
        myPostVar: myVar
    },
    type: 'POST'
});

And then this in the servlet (in the doGet):

String result = request.getParameter("myPostVar");
System.out.print(result);

And if i run the Test.java to test, it gives me "null". I googled too much but could not find any solution.


回答1:


The problem is you have the post method in your ajax and you are trying to get it in the doGet() of your servlet.

Use doPost or change the method to Get in your ajax.




回答2:


Try this:

public void doPost(HttpServletRequest request, HttpServletResponse response) 
   throws ServletException, IOException
{
    String myPostVar = request.getParameter("myPostVar");
    // ...
}


来源:https://stackoverflow.com/questions/28100431/how-to-pass-a-javascript-variable-to-a-java-servlet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!