如何从JavaScript向Servlet发送请求? [英] How can I send a request from JavaScript to a servlet?
问题描述
我有一个带JavaScript的.jsp文件.
I have a .jsp file with JavaScript.
如果单击确定"按钮,则会调用JavaScript方法.此方法检测ID.
If I click to the OK button, I call a JavaScript method. This method detects an id.
我想将此ID发送到我的servlet.在我的servlet中,我想使用getParameter(id)
获取ID.
I want to send this id to my servlet. In my servlet I want to get the id with getParameter(id)
.
我已经在本地计算机上实现了此功能,并且运行良好.如果我在服务器上部署源代码,则将调用JavaScript方法并检测到ID,但是该方法不会向我的Servlet发送请求.
I have implemented this on my local machine, and it functions well. If I deploy my source code on the sever, the JavaScript method will be called and the id will be detected, but the method doesn't send a request to my servlet.
<script language="text/javascript">
function removeLink(){
var id='';
var tmpcounter=0;
var check=0;
for (var counter = 0; counter < (document.getElementsByName("inProject[]").length); counter++) {
if (document.getElementsByName("inProject[]")[counter].checked) {
tmpcounter = tmpcounter+1;
}
}
for (var zaehler = 0; zaehler < (document.getElementsByName("inProject[]").length); zaehler++) {
if (document.getElementsByName("inProject[]")[zaehler].checked) {
check++;
if((check == tmpcounter) || (tmpcounter==1)){
id += 'id='+ document.getElementsByName("inProject[]")[zaehler].value;
}else{
id += 'id='+ document.getElementsByName("inProject[]")[zaehler].value +' OR ';
}
}
}
alert(id);
location.href='<%=request.getContextPath()%>/issues?action=uploaddeletelink&wherestatement=' + id;
close();
}
//-->
</script>
这是我的确定"按钮:
<td align='right'><a class='funktion' href='javascript:removeLink();'>OK<IMG src="<%=request.getContextPath()%>/issuedb/system/layout/funktionpfeil.gif" width="14" height="9" border="0"></a></td>
在我的服务器上,该函数将被调用,并且ID将被检测到.下面的代码行将请求发送到我的servlet,但是无法正常工作.
On my server, the function will be called, and the id will be detected. The line of code below, which sends the request to my servlet, doesn't function however.
location.href='<%=request.getContextPath()%>/issues?action=uploaddeletelink&wherestatement=' + id;
推荐答案
为此目的使用Jquery ajax,这很简单方便.您需要做的就是使用jquery插件.
Use Jquery ajax for this purpose, this is simple and handy. All you need to do is use jquery plugin.
function removeLink(){
$.ajax({
url: "<%=request.getContextPath()%>/issues?action=uploaddeletelink&wherestatement="+id,
type: "POST",
success: function(data){
//If you want to return anything in jsp.
}
});
}
希望这会有所帮助.
这篇关于如何从JavaScript向Servlet发送请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!