调用Servlet并从JavaScript调用Java代码以及参数
我有sessionkey,它是一个JavaScript变量,我从restapi调用中获得。我需要在servlet中调用Java代码,并将该键作为参数传递。我可以使用什么JavaScript函数来实现这一点?本身没有JavaScript函数,但浏览器通常*提供一个对象,您可以 例如,并提供帮助函数以简化其使用 *对于“通常”的值,它包含了几乎所有支持JavaScript的浏览器,并且是在Netscape 4去世后发布的。有几种方式:调用Servlet并从JavaScript调用Java代码以及参数,javascript,jsp,servlets,parameter-passing,Javascript,Jsp,Servlets,Parameter Passing,我有sessionkey,它是一个JavaScript变量,我从restapi调用中获得。我需要在servlet中调用Java代码,并将该键作为参数传递。我可以使用什么JavaScript函数来实现这一点?本身没有JavaScript函数,但浏览器通常*提供一个对象,您可以 例如,并提供帮助函数以简化其使用 *对于“通常”的值,它包含了几乎所有支持JavaScript的浏览器,并且是在Netscape 4去世后发布的。有几种方式: 使用window.location触发GET请求。需要注意的是,
window.location
触发GET请求。需要注意的是,它是同步的(因此客户端将看到当前页面被更改)
请注意内置的encodeURIComponent()
函数在传递请求参数之前对其进行编码的重要性form.submit()
触发GET或POST请求。注意事项还在于它是同步的
document.formname.key.value = key;
document.formname.submit();
与
下面的示例将调用servlet“sdoPost()
xhr
code仅在真实浏览器中工作,为了与MSIE兼容,您需要添加一些杂波;)
请注意,jQuery本身已经对请求参数进行了透明编码,因此这里不需要encodeURIComponent()
键
都将仅通过servlet中的request.getParameter(“键”)
可用
另见:
function executeRequest(req) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
document.getElementById("response").value = xhttp.responseText;
}
};
xhttp.open("POST", "execute/cardbrowser", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("lorem=ipsum&name=binny");
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println(req.getParameter("lorem"));
}
服务器:
function executeRequest(req) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
document.getElementById("response").value = xhttp.responseText;
}
};
xhttp.open("POST", "execute/cardbrowser", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("lorem=ipsum&name=binny");
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println(req.getParameter("lorem"));
}
$.get("http://example.com/servlet", { "key": key });
$.post("http://example.com/servlet", { "key": key });
function executeRequest(req) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
document.getElementById("response").value = xhttp.responseText;
}
};
xhttp.open("POST", "execute/cardbrowser", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("lorem=ipsum&name=binny");
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println(req.getParameter("lorem"));
}