工作需要,写了些ajax用于验证
摘抄一下:
action中:
public class CheckIPAction extends Action {
public ActionForward execute(ActionMapping maping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
String message = "hi";
response.setContentType("application/x-www-form-urlencoded;charset=UTF-8");
response.getWriter().write(message);
return null;
}
}
jsp中的<script>里:
//固定的,可写个js
function executeXhr(callback, url,info) {
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
req.onreadystatechange = callback;
req.open("POST", url, true);
req.setRequestHeader("Content-Length",info.length);
req.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
req.send("info");
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.onreadystatechange = callback;
req.open("POST", url, true);
req.setRequestHeader("Content-Length",info.length);
req.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
req.send(info);
}
}
}
function processAjaxResponse() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
var res = req.responseText;
doResponse(res);
} else {
alert("There was a problem retrieving the XML data:\n" +
req.statusText);
}
}
}
//下面是需要修改的
function sendRequest(){
var url = "./checkIPAction.do";
var callback = processAjaxResponse;
var queryStr = "ips=1";
executeXhr(callback, url,queryStr);
}
function doResponse(response){
msg.innerHTML = response;
}