Home >Web Front-end >JS Tutorial >js calls background servlet method instance_javascript skills

js calls background servlet method instance_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:32:382880browse

1. Use document.form.action method

The relevant source code is as follows:

*.js

[javascript]

Copy code The code is as follows:

document.getElementById("sendPerson").value = SendPerson;
document.getElementById("currentTime").value = currentTime();
document.getElementById ("message").value = message;
document.getElementById("recvPerson").value = recvPerson;
document.chatform.action = "ToHistoryServlet";
document.chatform.submit();
*.html

[html]
Copy code The code is as follows:


type="hidden" name="currentTime" id="currentTime"> type="hidden" name="message" id="message"> < input
            type="hidden" name="recvPerson" id="recvPerson">

Note that input needs to specify the name attribute so that the servlet can obtain the parameter value
*.java

[java]

Copy code The code is as follows:

public void doPost(HttpServletRequest request , HttpServletResponse response)
throws ServletException, IOException { www.jb51.net

String sendPerson = request.getParameter("sendPerson");
String recvPerson = request.getParameter("recvPerson");
String sendTime = request.getParameter("currentTime");
String message = request.getParameter("message");
Message msg = new Message();
msg.setMessage(message) ;
msg.setRecvPerson(recvPerson);
msg.setSendPerson(sendPerson);
msg.setSendTime(sendTime);
HistoryHandle.addMessage(msg);
}

The disadvantage of this is that the page jumps away. If you want to keep the original page, you can refer to method 2

2.jquery calls background method

[javascript]

Copy code The code is as follows:

$.ajax({
type : "POST",
contentType : "application/json",
url : "ToHistoryServlet?sendPerson=" SendPerson "¤tTime="
currentTime() "&message=" message "&recvPerson= "
recvPerson,
dataType : 'json',
success : function(result) {
alert(result.d);
}
});

The code size is small and easy to use. It is worth recommending. . .
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn