如何通过一个javascript变量一个Java servlet?

如何通过一个javascript变量一个Java servlet?

问题描述:

我想一个JavaScript变量传递给一个Java servlet。我开发一个Web应用程序。这是我的HTML code:

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>

这是我写的JavaScript文件:

And this is what i write in the javascript file:

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

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

和那么这在servlet(中的doGet):

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

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

,如果我运行Test.java进行测试,它给了我空。我GOOGLE了太多,但找不到任何解决办法。

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

现在的问题是你有方法在你的AJAX和你正在试图让它在的doGet()你的servlet的。

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

使用的doPost 或改变方法获取在阿贾克斯。

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