js 异步请求

Posted 墨初

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了js 异步请求相关的知识,希望对你有一定的参考价值。

<p id="check">
	<label>验证码:</label>
	<input  class="vid" id="ValidateCode" name="ValidateCode"  type="text" value="" onblur="checkValidateCode()"/>
	<img id="checkcodeimg" src="<%=path %>/image.jsp" style="margin-left:10px;" width="74px" height="28px"  onclick="this.src=‘<%=path %>/image.jsp?date=‘+new Date();"/>
	<span id="codeSpan"></span>
</p>

image.jsp

 1 <%@ page contentType="image/jpeg" import="java.awt.*, java.awt.image.*,java.util.*,javax.imageio.*"%>
 2 <%!Color getRandColor(int fc, int bc) {
 3         Random random = new Random();
 4         if (fc > 255)
 5             fc = 255;
 6         if (bc > 255)
 7             bc = 255;
 8         int r = fc + random.nextInt(bc - fc);
 9         int g = fc + random.nextInt(bc - fc);
10         int b = fc + random.nextInt(bc - fc);
11         return new Color(r, g, b);
12     }%>
13 <%
14     out.clear();//????resin???????tomacat??????
15     out = pageContext.pushBody();
16     response.setHeader("Pragma", "No-cache");
17     response.setHeader("Cache-Control", "no-cache");
18     response.setDateHeader("Expires", 0);
19 
20     int width = 60, height = 20;
21     BufferedImage image = new BufferedImage(width, height,
22             BufferedImage.TYPE_INT_RGB);
23 
24     Graphics g = image.getGraphics();
25     Random random = new Random();
26 
27     g.setColor(getRandColor(200, 250));
28     g.fillRect(0, 0, width, height);
29 
30     g.setFont(new Font("Times New Roman", Font.PLAIN, 18));
31 
32     g.setColor(getRandColor(160, 200));
33     for (int i = 0; i < 155; i++) {
34         int x = random.nextInt(width);
35         int y = random.nextInt(height);
36         int xl = random.nextInt(12);
37         int yl = random.nextInt(12);
38         g.drawLine(x, y, x + xl, y + yl);
39     }
40 
41     String sRand = "";
42     for (int i = 0; i < 4; i++) {
43         String rand = String.valueOf(random.nextInt(10));
44         sRand += rand;
45 
46         g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
47         g.drawString(rand, 13 * i + 6, 16);
48     }
49     // ??????SESSION
50     session.setAttribute("rand", sRand);
51     g.dispose();
52 
53     ImageIO.write(image, "JPEG", response.getOutputStream());
54 %>

 

  

实现jsp

 

 1  var xmlHttpRequest;   
 2     //XmlHttpRequest对象   
 3     function createXmlHttpRequest(){   
 4         if(window.ActiveXObject){ //如果是IE
 5             return new ActiveXObject("Microsoft.XMLHTTP");   
 6         }else if(window.XMLHttpRequest){ //非IE浏览器   
 7             return new XMLHttpRequest();   
 8         }   
 9     }   
10      function checkValidateCode(){
11         code = document.getElementById("ValidateCode").value.trim();
12         var url = "user_validateCodeCheck.do?validateCode="+code;
13         xmlHttpRequest = createXmlHttpRequest(); 
14         xmlHttpRequest.onreadystatechange = HuiDiaoFun; 
15         xmlHttpRequest.open("post",url,true); 
16         xmlHttpRequest.send(null);  
17     }
18             
19     //回调函数   
20     function HuiDiaoFun(){   
21         if(xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200){
22             var resp = xmlHttpRequest.responseText;
23             if (resp == "error") {
24                 document.getElementById("codeSpan").innerhtml = "验证码错误!";
25                 document.getElementById("codeSpan").style.color = "#FF0000";
26             }else if(resp == "ok"){
27                 document.getElementById("codeSpan").innerHTML = "";
28             }
29         }   
30     }  
  1 public class UserAction extends BaseAction{
  2     
  3 
  4     private String validateCode;
  5 
  6     
  7     public void validateCodeCheck(){
  8         String code = (String)getHttpSession().getAttribute("rand");
  9         System.out.println(code);
 10         if(StringUtils.isNoneEmpty(validateCode) && validateCode.equals(code)){
 11             ResponseUtil.writeUTF(getHttpResponse(), "ok");
 12         }else{
 13             ResponseUtil.writeUTF(getHttpResponse(), "error");
 14         }
 15     }
 16     
 17 }
 18 
 19 
 20 
 21 
 22 import java.io.IOException;
 23 import java.io.UnsupportedEncodingException;
 24 import java.util.Enumeration;
 25 import java.util.HashMap;
 26 import java.util.List;
 27 import java.util.Map;
 28 
 29 import javax.servlet.ServletContext;
 30 import javax.servlet.http.HttpServletRequest;
 31 import javax.servlet.http.HttpServletResponse;
 32 import javax.servlet.http.HttpSession;
 33 import javax.servlet.jsp.PageContext;
 34 
 35 import org.apache.struts2.ServletActionContext;
 36 import org.springframework.web.context.support.WebApplicationContextUtils;
 37 
 38 import com.opensymphony.xwork2.ActionSupport;
 39 
 40 
 41 
 42 /**
 43  * action基类,提供共用方法
 44  * 
 45  *
 46  */
 47 public class BaseAction extends ActionSupport {
 48 
 49     public UnitService baseUnitService;
 50     public RoleService baseRoleService;
 51     public ConfigService baseConfigService;
 52     public ChannelService baseChannelService;
 53     public InfoService baseInfoService;
 54     public int pageSize=10;
 55     public int currPage=1;
 56     public int totalCount=0;
 57     public String pageStr;
 58     public String pageFuncId;
 59     public String showMessage;
 60     public String forwardUrl="";
 61     public int forwardSeconds=0;
 62     public String getForwardUrl() {
 63         return forwardUrl;
 64     }
 65     public void setForwardUrl(String forwardUrl) {
 66         this.forwardUrl = forwardUrl;
 67     }
 68     public int getForwardSeconds() {
 69         return forwardSeconds;
 70     }
 71     public void setForwardSeconds(int forwardSeconds) {
 72         this.forwardSeconds = forwardSeconds;
 73     }
 74     public int getPageSize() {
 75         return pageSize;
 76     }
 77     public void setPageSize(int pageSize) {
 78         this.pageSize = pageSize;
 79     }
 80     public int getCurrPage() {
 81         return currPage;
 82     }
 83     public void setCurrPage(int currPage) {
 84         this.currPage = currPage;
 85     }
 86     public HttpSession getHttpSession(){
 87         return ServletActionContext.getRequest().getSession();
 88     }
 89     public HttpServletRequest getHttpRequest(){
 90         return ServletActionContext.getRequest();
 91     }
 92     public HttpServletResponse getHttpResponse(){
 93         return ServletActionContext.getResponse();
 94     }
 95     public PageContext getPageContext(){
 96         return ServletActionContext.getPageContext();
 97     }
 98     public ServletContext getServletContext(){
 99         return ServletActionContext.getServletContext();
100     }
101     public Map<String, Object> getApplication(){
102         return ServletActionContext.getContext().getApplication();
103     }
104     public String getBasePath(){
105         String path = getHttpRequest().getContextPath();
106         String basePath = getHttpRequest().getScheme()+"://"+getHttpRequest().getServerName()+":"+getHttpRequest().getServerPort()+path+"/";
107         return basePath;
108     }
109     
110     
111     /**
112      * 获取配置
113      * @return
114      */
115     public Map<String, Object> getConfig(){
116         if (getApplication().get("config")!=null) {
117             return (Map<String, Object>)getApplication().get("config");
118         }else {
119             //重新生成
120             return setConfig();
121         }
122     }
123     /**
124      * 获取配置值 
125      * @return
126      */
127     public String getConfigVal(String name){
128         Map<String, Object> config=getConfig();
129         if (config!=null && config.get(name)!=null) {
130             return config.get(name).toString();
131         }
132         return "";
133     }
134     /**
135      * 设置配置
136      * @return
137      */
138     public Map<String, Object> setConfig(){
139          baseConfigService = (ConfigService) getBean("configService");
140         List<Config> configList=baseConfigService.find();
141         Map<String, Object> config=new HashMap<String, Object>();
142         if (configList!=null && configList.size()>0) {
143             for (int i = 0; i < configList.size(); i++) {
144                 config.put(configList.get(i).getCode(), configList.get(i).getConfigvalue());
145             }
146         }
147         getApplication().put("config", config);
148         return config;
149     }
150     public void write(String content,String charset){
151         getHttpResponse().setCharacterEncoding(charset);
152         getHttpResponse().setContentType("text/html;charset="+charset);
153         try {
154             getHttpResponse().getWriter().print(content);
155         } catch (IOException e) {
156             e.printStackTrace();
157         }
158     }
159     /**
160      * 判断是否为admin登录
161      */
162     public boolean isAdminLogin(){
163         return "admin".equals(getLoginName());
164     }
165     /**
166      * 判断是否为站点总管理员
167      */
168     public boolean isSiteAdmin(){
169         if (getHttpSession().getAttribute("siteAdmin")!=null) {
170             return (Boolean)getHttpSession().getAttribute("siteAdmin");
171         }
172         return false;
173     }
174     /**
175      * 获取当前管理站点 
176      * @return
177      */
178     public Site getManageSite(){
179         if (getHttpSession().getAttribute("manageSite")!=null) {
180             //获取当前管理站点
181             return (Site)getHttpSession().getAttribute("manageSite");
182         }
183         return null;
184     }
185     /**
186      * 获取session中的当前登录用户名
187      * @return
188      */
189     public String getLoginName(){
190         if (getLoginAdmin()!=null) {
191             return getLoginAdmin().getLoginname();
192         }
193         return "";
194     }
195     /**
196      * 获取session中的当前登录用户
197      * @return
198      */
199     public Users getLoginAdmin(){
200         if (getHttpSession().getAttribute("loginAdmin")!=null) {
201             return (Users)getHttpSession().getAttribute("loginAdmin");
202         }
203         return null;
204     }
205     /**
206      * 获取session中的当前登录会员
207      * @return
208      */
209     public Member getLoginMember(){
210         if (getHttpSession().getAttribute("loginMember")!=null) {
211             return (Member)getHttpSession().getAttribute("loginMember");
212         }
213         return null;
214     }
215     /**
216      * 获取session中的当前登录会员组
217      * @return
218      */
219     public Membergroup getLoginMembergroup(){
220         if (getHttpSession().getAttribute("loginMembergroup")!=null) {
221             return (Membergroup)getHttpSession().getAttribute("loginMembergroup");
222         }
223         return null;
224     }
225     /**
226      * 获取session中的当前会员登录用户名
227      * @return
228      */
229     public String getLoginMemberName(){
230         if (getLoginMember()!=null) {
231             return getLoginMember().getLoginname();
232         }
233         return "";
234     }
235     
236     /**
237      * 获取登录用户所属单位
238      * @return
239      */
240     public List<Unit> getLoginUnits(){
241         //先判断session是否存在
242         HttpSession session=getHttpSession();
243         if (session.getAttribute("loginUnits")!=null) {
244             return (List<Unit>)session.getAttribute("loginUnits");
245         }else {
246             //不存在则重新提取
247             baseUnitService = (UnitService) getBean("unitService");
248             List<Unit> list = baseUnitService.findByUser(getLoginAdmin().getId());
249             session.setAttribute("loginUnits", list);
250             return list;
251         }
252     }
253     /**
254      * 获取登录用户所属单位组成的sql语句
255      * 例:‘‘,‘‘,‘‘
256      * @return
257      */
258     public String getLoginUnitIdsSql(){
259         List<Unit> list=getLoginUnits();
260         StringBuilder sb=new StringBuilder();
261         if (list!=null && list.size()>0) {
262             for (int i = 0; i < list.size(); i++) {
263                 if (i>0) {
264                     sb.append(",");
265                 }
266                 sb.append("‘"+list.get(i).getId()+"‘");
267             }
268         }
269         return sb.toString();
270     }
271     /**
272      * 获取登录用户所属角色
273      * @return
274      */
275     public List<Roles> getLoginRoles(){
276         //先判断session是否存在
277         HttpSession session=getHttpSession();
278         if (session.getAttribute("loginRoles")!=null) {
279             return (List<Roles>)session.getAttribute("loginRoles");
280         }else {
281             //不存在则重新提取
282             baseRoleService = (RoleService) getBean("roleService");
283             List<Roles> list = baseRoleService.findByUser(getLoginAdmin().getId());
284             session.setAttribute("loginRoles", list);
285             return list;
286         }
287     }
288     /**
289      * 获取登录用户所属角色组成的sql语句
290      * 例:‘‘,‘‘,‘‘
291      * @return
292      */
293     public String getLoginRoleIdsSql(){
294         List<Roles> list=getLoginRoles();
295         StringBuilder sb=new StringBuilder();
296         if (list!=null && list.size()>0) {
297             for (int i = 0; i < list.size(); i++) {
298                 if (i>0) {
299                     sb.append(",");
300                 }
301                 sb.append("‘"+list.get(i).getId()+"‘");
302             }
303         }
304         return sb.toString();
305     }
306     /**
307      * 返回到通用信息提示页面
308      * @param msg
309      * @param url
310      * @param seconds
311      * @return
312      */
313     public String showMessage(String showMessage,String forwardUrl,int forwardSeconds){
314         this.showMessage=showMessage;
315         this.forwardUrl=forwardUrl;
316         this.forwardSeconds=forwardSeconds;
317         return "showMessage";
318     }
319     /**
320      * 设置静态化参数
321      * @param data
322      * @throws UnsupportedEncodingException 
323      */
324     public void setData(Map<String,Object> data,Site site) throws UnsupportedEncodingException{
325         //传递site参数
326         data.put("site", site);
327         data.put("contextPath", getContextPath());
328         data.put("contextPathNo", getContextPathNo());
329         data.put("request_remoteAddr", getHttpRequest().getRemoteAddr());
330         //获取参数并放入data
331         Enumeration<String> paramNames=getHttpRequest().getParameterNames();
332         if (paramNames!=null && paramNames.hasMoreElements()) {
333             String name;
334             while (paramNames.hasMoreElements()) {
335                 name=paramNames.nextElement();
336                 if (name!=null &&
337                         !name.equals("site") &&
338                         !name.equals("contextPath")&&
339                         !name.equals("currChannelid")&&
340                         !name.equals("currInfoid")) {
341                     if(name.equals("key")){
342                         String key = new String(getHttpRequest().getParameter(name).getBytes(),"UTF-8");
343                         data.put(name, key);
344                     }else{
345                         data.put(name, getHttpRequest().getParameter(name));
346                     }
347                 }
348             }
349         }
350         //如果有currChannelid参数则传递currChannel对象
351         if (getHttpRequest().getParameter("currChannelid")!=null && getHttpRequest().getParameter("currChannelid").trim().length()>0) {
352             baseChannelService = (ChannelService) getBean("channelService");
353             data.put("currChannel",baseChannelService.findById(getHttpRequest().getParameter("currChannelid")));
354         }
355         //如果有currInfoid参数则传递currInfo对象
356         if (getHttpRequest().getParameter("currInfoid")!=null && getHttpRequest().getParameter("currInfoid").trim().length()>0) {
357             baseInfoService = (InfoService) getBean("infoService");
358             data.put("currInfo",baseInfoService.findById(getHttpRequest().getParameter("currInfoid")));
359         }
360         //获取seesion中存放的变量
361         Enumeration<String> sessionNames=getHttpSession().getAttributeNames();
362         if (sessionNames!=null && sessionNames.hasMoreElements()) {
363             String name;
364             while (sessionNames.hasMoreElements()) {
365                 name=sessionNames.nextElement();
366                 if (name!=null) {
367                     //session变量名称改为session_变量名,避免重名
368                     data.put("session_"+name, getHttpSession().getAttribute(name));
369                 }
370             }
371         }
372     }
373     public String getContextPath(){
374         return getHttpRequest().getContextPath()+"/";
375     }
376     public String getContextPathNo(){
377         return getHttpRequest().getContextPath()+"/";
378     }
379     public String getPageStr() {
380         return pageStr;
381     }
382     public void setPageStr(String pageStr) {
383         this.pageStr = pageStr;
384     }
385     public int getTotalCount() {
386         return totalCount;
387     }
388     public void setTotalCount(int totalCount) {
389         this.totalCount = totalCount;
390     }
391     public String getPageFuncId() {
392         return pageFuncId;
393     }
394     public void setPageFuncId(String pageFuncId) {
395         this.pageFuncId = pageFuncId;
396     }
397     public UnitService getBaseUnitService() {
398         return baseUnitService;
399     }
400     public void setBaseUnitService(UnitService baseUnitService) {
401         this.baseUnitService = baseUnitService;
402     }
403     public RoleService getBaseRoleService() {
404         return baseRoleService;
405     }
406     public 以上是关于js 异步请求的主要内容,如果未能解决你的问题,请参考以下文章

jQuery-异步请求

在哪里以及如何使用片段填充我的标签

我应该在 Fragment 中的啥生命周期状态下执行异步任务?

js异步请求发展史和yield

在Nuxt.js组件中获取异步数据

回归 | js实用代码片段的封装与总结(持续更新中...)