一个简单的AJAX
JS脚本:
//页面调用方法
function getInfo(obj){
var ajax=getAjaxObject();
url="ajaxAction.do?method=ajaxCheck";
ajax.onreadystatechange =function(){
var buffer="";
if (ajax.readyState == 4&&ajax.status == 200){
buffer=ajax.responseText;
//*回调调用方法
ajaxCallback(buffer);
}
}
ajax.open("POST",url);
ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
ajax.send("para="+obj);
}
//*get Ajax Object
function getAjaxObject(){
if (window.ActiveXObject) {
try{
ajax = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
alert("创建Microsoft.XMLHTTP对象失败,AJAX不能正常运行.请检查您的浏览器设置.");
}
} else {
if (window.XMLHttpRequest) {
try{
ajax = new XMLHttpRequest();
}catch(e){
alert("创建XMLHttpRequest对象失败,AJAX不能正常运行.请检查您的浏览器设置.");
}
}
}
return ajax;
}
struts1.x action:
public ActionForward ajaxCheck(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response){
PrintWriter writer;
response.setContentType("text/plain;charset=GBK");
response.setHeader("Pragma","No-Cache");
response.setHeader("Cache-Control","No-Cache");
response.setDateHeader("Expires", 0);
boolean enable=false;
try{
writer=response.getWriter();
AjaxService ajax=new AjaxService ();
String para=request.getParameter("para");
enable = ajax.checkSomething(para);
} catch (Exception e) {
log.error(e.getMessage());
return mapping.findForward("exception");
}
writer.print(enable);
writer.close();
return null;
}
备注:
如果需要向页面返回一个JS对象,可以在java中拼装一个对象字符串({name:'jack',sex:'m'}),在前台得到这个字符串后将其转换成一个JS对象(var obj=null; eval("obj="+outputString); return obj;)。