javascript異歩要求、getとpost
4165 ワード
post
<script type="text/javascript" src="/js/jquery-1.8.3.js"></script>
<script type="text/javascript">
// : XMLHttpRequest 。(ActiveXObject)
(function(){
// MSIE8+、firefox、opera、chrome
if (window.XMLHttpRequest){
window.xhr = new XMLHttpRequest();
}else{ // msie7 (ActiveXObject)
// ActiveX
var xmls = ["MSXML2.XMLHTTP.7.0",
"MSXML2.XMLHTTP.6.0",
"MSXML2.XMLHTTP.5.0",
"Microsoft.XMLHTTP"];
for (var i = 0; i < xmls.length; i++){
try{
window.xhr = new s(xmls[i]);
break;
}catch(ex){
alert(ex);
}
}
}
})();
window.onload = function(){
document.getElementById("btn").onclick = function(){
//
var userId = document.getElementById("userId").value;
//
var pwd = document.getElementById("pwd").value;
// : 。
// : (get|post)
// : url
// : true: false:
xhr.open("post", "post.action", true);
// post
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
// :
xhr.send("userId=" + userId + "&pwd=" + pwd);
// xhr
xhr.onreadystatechange = function(){
//alert(xhr.readyState);
if (xhr.readyState == 4){ //
alert(xhr.status);
if (xhr.status == 200){ //
//
alert(xhr.responseText);
}
}
};
};
};
</script>
get <script type="text/javascript">
// : XMLHttpRequest 。(ActiveXObject)
(function(){
// MSIE8+、firefox、opera、chrome
if (window.XMLHttpRequest){
window.xhr = new XMLHttpRequest();
}else{ // msie7 (ActiveXObject)
// ActiveX
var xmls = ["MSXML2.XMLHTTP.7.0",
"MSXML2.XMLHTTP.6.0",
"MSXML2.XMLHTTP.5.0",
"Microsoft.XMLHTTP"];
for (var i = 0; i < xmls.length; i++){
try{
window.xhr = new s(xmls[i]);
break;
}catch(ex){
alert(ex);
}
}
}
})();
window.onload = function(){
document.getElementById("btn").onclick = function(){
//
var userId = document.getElementById("userId").value;
//
var pwd = document.getElementById("pwd").value;
// : 。
// : (get|post)
// : url
// : true: false:
xhr.open("get", "login.action?userId=" + userId + "&pwd=" + pwd, true);
// :
xhr.send();
// xhr
xhr.onreadystatechange = function(){
//alert(xhr.readyState);
if (xhr.readyState == 4){ //
alert(xhr.status);
if (xhr.status == 200){ //
//
alert(xhr.responseText);
}
}
};
};
};
</script>
<input type="text" name="userId" id="userId"/>
<input type="password" name="pwd" id="pwd"/>
<input type="button" id="btn" value=" "/>
@WebServlet("/post.action")
public class PostServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");// post
String userId = request.getParameter("userId");
String pwd = request.getParameter("pwd");
System.out.println(userId + "---" + pwd);
response.setContentType("text/html; charset=utf-8");
response.getWriter().print(" :" + userId);
}
}