小白我最近开始研究Ajax,从头开始,用到Struts2+Ajax返回文本字符串的时候发现网上用原生JavaScript实现的并不是很多,多半是Struts2+Ajax+JQuery+JSON等实现的。所以小白写了一篇小文,献丑了。
如果有什么不妥的地方,请各位大神批评指正,谢谢。
本文例子主要是实现用户输入用户名之后,当输入框失去焦点的时候检测用户名是否已经存在。
用户页面,register.html:
<li> <div class="inputInfo"> <span>帐号</span> <input type="text" value="" class="inputText" id="name"/> </div> </li> <li> <div class="inputInfo"> <span>密码</span> <input type="password" class="inputText" id="password"/> </div> </li> <!-- 显示返回文本字符串 --> <div id="showResponseText"></div>
??
工具包utils.js用来获取请求request。utils.js:
// JavaScript Document utils={ createRequest:function(){ var request ; try{ request = new XMLHttpRequest(); }catch(tryMS){ try{ request = new ActiveXObject("Msxml2.XMLHTTP"); }catch(otherMS){ try{ request = new ActiveXObject("Microsoft.XMLHTTP"); }catch(failed){ request = null; } } } return request; } };
?
脚本操作,register.js
// JavaScript Document register={ init:function(){ document.getElementById('name').onblur = register.checkUserName; }, checkUserName:function(){ request = utils.createRequest(); if(request == null){ alert("create request failed"); } else{ var nameValue = document.getElementById('name').value; var url = "ajax_register!checkUserName?userName="+nameValue; request.onreadystatechange = register.showUserNameStatus; request.open("post",url,true); request.send(null); } }, showUserNameStatus:function(){ if(request.readyState == 4){ if(request.status ==200){ document.getElementById("ppt").innerHTML=request.responseText; } } } }; window.onload = register.init;
?
Struts2的配置文件编写,Struts.xml:
<action name="ajax_register" class="customer.action.Ajax_RegisterAction"> <result type="stream"> <param name="contentType">text/plain</param> <param name="inputName">inputStream</param> </result> </action>
action的编写,Ajax_RegisterAction.java:
import java.io.InputStream; import java.io.StringBufferInputStream; import com.opensymphony.xwork2.ActionSupport; import customer.service.Register; import customer.service.RegisterImpl; public class Ajax_RegisterAction extends ActionSupport { /** * */ private static final long serialVersionUID = 1L; private InputStream inputStream; public InputStream getInputStream() { return inputStream; } public void setInputStream(InputStream inputStream) { this.inputStream = inputStream; } // service类 private Register register = new RegisterImpl(); private String userName; public String getUserName() { return userName; } // 检查userName是否重复 public String checkUserName(){ String text =""; if(!register.checkNameExist(userName)){ text = "yes"; }else{ text = "no"; } getResponseText(text); return SUCCESS; } // 获取返回文本 public void getResponseText(String text){ inputStream = new StringBufferInputStream(text); }?
?
上面关于xml的配置以及action的编码在Strust2帮助文档(点击这里在线查看)里面都有。
好了,基本就这样了,如果有什么不妥的地方,请各位大神批评指正,谢谢。
(文/sbpcx)