java深入探究13-js,ajax
链接:http://pan.baidu.com/s/1c2D0cAs 密码:uwm6
1.js
1)三种基本类型:
var num=100;
var str="哈哈";
var flag=true;
2)创建函数的三种方式:
正常模式:
function add(num1,num2){
return num1+num2;
}
构造器模式:
var add=new Function("num1","num2","return num1+num2");
匿名方式:
var add=function(num1,num2){return num1=num2;}
3)js中的对象
Date;String;Array;Math;自定义对象;window对象;status对象,location对象,history对象
<script type="text/javascript">
//Date
/* var nowStr=new Date().toLocaleDateString();
window.alert(nowStr); */ //String
/* var str="String";
var length=str.length;
window.alert(length); */ //Array
/* var array=new Array("语文","数学","英语",true,123);
for(var i=0;i<array.length;i++){
document.write(array[i] + " ");
} */ //Math
/* for(var i=1;i<=10;i++){
document.write(Math.floor(Math.random()*9)+1 + "<br/>");
} */ //自定义对象
function Person(id,name,sal){
this.id=id;
this.name=name;
this.sal=sal;
}
var p =new Person(,"小平",);
document.write("编号:"+p.id+"<br/>");
document.write("姓名:"+p.name+"<br/>");
document.write("薪水:"+p.sal+"<br/>"); //window对象
/* var url = "04_images.html";
window.open(url); */ //status对象,将当前时间设置到状态栏
/* var nowStr = new Date().toLocaleString();
window.status = nowStr; */ //location对象,模拟用户在地址栏输入url访问其它页面的情况
/* var url="04_images.html";
window.location.href=url; */ //history
/* window.history.go(1); */
</script>
2.ajax
创建ajax通用函数
function createAJAX(){
var ajax = null;
try{
ajax = new ActiveXObject("microsoft.xmlhttp");
}catch(e1){
try{
ajax = new XMLHttpRequest();
}catch(e2){
alert("你的浏览器不支持ajax,请更换浏览器");
}
}
return ajax;
}
get方式发送数据给servlet
需要注意点:get方式数据传输是靠url,所有传输中文时,需要转码,encodeURI();,之后到了后台需要将数据转为byte以ISO8859-1方式,再变为utf-8模式字符串
<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>基于HTML,以GET或POST方式,检查注册用户名是否在数据库中已存在</title>
</head>
<body> <form>
用户名[GET]:<input id="usernameID" type="text" name="username" maxlength=""/>
光标移出后,立即检查结果
</form>
<hr/>
<span id="resID"></span> <script type="text/javascript">
//创建AJAX异步对象,即XMLHttpRequest
function createAJAX(){
var ajax = null;
try{
ajax = new ActiveXObject("microsoft.xmlhttp");
}catch(e1){
try{
ajax = new XMLHttpRequest();
}catch(e2){
alert("你的浏览器不支持ajax,请更换浏览器");
}
}
return ajax;
}
</script> <script type="text/javascript">
//定位文本框,同时提供焦点失去事件
document.getElementById("usernameID").onblur = function(){
//获取文本框中输入的值
var username = this.value;
//如果用户没有填内容
if(username.length == ){
//提示
document.getElementById("resID").innerHTML = "用户名必填";
}else{
//对汉字进行UTF-8(U8)的编码
username = encodeURI(username);
//NO1)
var ajax = createAJAX();
//NO2)
var method = "GET";
var url = "${pageContext.request.contextPath}/UserServlet?time="+new Date().getTime()+"&username=" + username;
//alert(url);
ajax.open(method,url);
//NO3)
ajax.send(null); //--------------------------------------------------------等待 //NO4)
ajax.onreadystatechange = function(){
if(ajax.readyState == ){
if(ajax.status == ){
//NO5)
var tip = ajax.responseText;
//NO6)
document.getElementById("resID").innerHTML = tip;
}
}
}
}
}
</script> </body>
</html>
post方式发送数据给servlet
需要注意点:因为ajax传数据到后台默认是get方式,一般会访问完url就就结束,所以为了能将content数据通过send发过去,需要给ajax设置请求头ajax.setRequestHeader("content-type","application/x-www-form-urlencoded")
<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>基于HTML,以GET或POST方式,检查注册用户名是否在数据库中已存在</title>
</head>
<body> <form>
用户名[POST]:<input id="usernameID" type="text" name="username" maxlength=""/>
光标移出后,立即检查结果
</form>
<hr/>
<span id="resID"></span> <script type="text/javascript">
//创建AJAX异步对象,即XMLHttpRequest
function createAJAX(){
var ajax = null;
try{
ajax = new ActiveXObject("microsoft.xmlhttp");
}catch(e1){
try{
ajax = new XMLHttpRequest();
}catch(e2){
alert("你的浏览器不支持ajax,请更换浏览器");
}
}
return ajax;
}
</script> <script type="text/javascript">
//定位文本框,同时提供焦点失去事件
document.getElementById("usernameID").onblur = function(){
//获取文本框中输入的值
var username = this.value;
//如果用户没有填内容
if(username.length == ){
//提示
document.getElementById("resID").innerHTML = "用户名必填";
}else{
var ajax = createAJAX();
var method = "POST";
var url = "${pageContext.request.contextPath}/UserServlet";
//alert(url);
ajax.open(method,url); //需要设置ajax请求头,因为这是ajax模式是get方式请求,访问完uri后就不访问,且会自动将请求体重汉字自动转换为UTF-8
ajax.setRequestHeader("content-type","application/x-www-form-urlencoded")
var content="username="username;
//NO3)
ajax.send(content); //--------------------------------------------------------等待 //NO4)
ajax.onreadystatechange = function(){
if(ajax.readyState == ){
if(ajax.status == ){
//NO5)
var tip = ajax.responseText;
//NO6)
document.getElementById("resID").innerHTML = tip;
}
}
}
}
}
</script> </body>
</html>
3.json
将对象转为json对象可用JSONObject(阿里封装的json)
/*
* Copyright 1999-2101 Alibaba Group.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.fastjson; import static com.alibaba.fastjson.util.TypeUtils.castToBigDecimal;
import static com.alibaba.fastjson.util.TypeUtils.castToBigInteger;
import static com.alibaba.fastjson.util.TypeUtils.castToBoolean;
import static com.alibaba.fastjson.util.TypeUtils.castToByte;
import static com.alibaba.fastjson.util.TypeUtils.castToBytes;
import static com.alibaba.fastjson.util.TypeUtils.castToDate;
import static com.alibaba.fastjson.util.TypeUtils.castToDouble;
import static com.alibaba.fastjson.util.TypeUtils.castToFloat;
import static com.alibaba.fastjson.util.TypeUtils.castToInt;
import static com.alibaba.fastjson.util.TypeUtils.castToLong;
import static com.alibaba.fastjson.util.TypeUtils.castToShort;
import static com.alibaba.fastjson.util.TypeUtils.castToSqlDate;
import static com.alibaba.fastjson.util.TypeUtils.castToTimestamp; import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set; import com.alibaba.fastjson.annotation.JSONField;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.util.TypeUtils; /**
* @author wenshao[szujobs@hotmail.com]
*/
public class JSONObject extends JSON implements Map<String, Object>, Cloneable, Serializable, InvocationHandler { private static final long serialVersionUID = 1L;
private static final int DEFAULT_INITIAL_CAPACITY = ; private final Map<String, Object> map; public JSONObject(){
this(DEFAULT_INITIAL_CAPACITY, false);
} public JSONObject(Map<String, Object> map){
this.map = map;
} public JSONObject(boolean ordered){
this(DEFAULT_INITIAL_CAPACITY, ordered);
} public JSONObject(int initialCapacity){
this(initialCapacity, false);
} public JSONObject(int initialCapacity, boolean ordered){
if (ordered) {
map = new LinkedHashMap<String, Object>(initialCapacity);
} else {
map = new HashMap<String, Object>(initialCapacity);
}
} public int size() {
return map.size();
} public boolean isEmpty() {
return map.isEmpty();
} public boolean containsKey(Object key) {
return map.containsKey(key);
} public boolean containsValue(Object value) {
return map.containsValue(value);
} public Object get(Object key) {
return map.get(key);
} public JSONObject getJSONObject(String key) {
Object value = map.get(key); if (value instanceof JSONObject) {
return (JSONObject) value;
} return (JSONObject) toJSON(value);
} public JSONArray getJSONArray(String key) {
Object value = map.get(key); if (value instanceof JSONArray) {
return (JSONArray) value;
} return (JSONArray) toJSON(value);
} public <T> T getObject(String key, Class<T> clazz) {
Object obj = map.get(key);
return TypeUtils.castToJavaBean(obj, clazz);
} public Boolean getBoolean(String key) {
Object value = get(key); if (value == null) {
return null;
} return castToBoolean(value);
} public byte[] getBytes(String key) {
Object value = get(key); if (value == null) {
return null;
} return castToBytes(value);
} public boolean getBooleanValue(String key) {
Object value = get(key); if (value == null) {
return false;
} return castToBoolean(value).booleanValue();
} public Byte getByte(String key) {
Object value = get(key); return castToByte(value);
} public byte getByteValue(String key) {
Object value = get(key); if (value == null) {
return ;
} return castToByte(value).byteValue();
} public Short getShort(String key) {
Object value = get(key); return castToShort(value);
} public short getShortValue(String key) {
Object value = get(key); if (value == null) {
return ;
} return castToShort(value).shortValue();
} public Integer getInteger(String key) {
Object value = get(key); return castToInt(value);
} public int getIntValue(String key) {
Object value = get(key); if (value == null) {
return ;
} return castToInt(value).intValue();
} public Long getLong(String key) {
Object value = get(key); return castToLong(value);
} public long getLongValue(String key) {
Object value = get(key); if (value == null) {
return 0L;
} return castToLong(value).longValue();
} public Float getFloat(String key) {
Object value = get(key); return castToFloat(value);
} public float getFloatValue(String key) {
Object value = get(key); if (value == null) {
return 0F;
} return castToFloat(value).floatValue();
} public Double getDouble(String key) {
Object value = get(key); return castToDouble(value);
} public double getDoubleValue(String key) {
Object value = get(key); if (value == null) {
return 0D;
} return castToDouble(value);
} public BigDecimal getBigDecimal(String key) {
Object value = get(key); return castToBigDecimal(value);
} public BigInteger getBigInteger(String key) {
Object value = get(key); return castToBigInteger(value);
} public String getString(String key) {
Object value = get(key); if (value == null) {
return null;
} return value.toString();
} public Date getDate(String key) {
Object value = get(key); return castToDate(value);
} public java.sql.Date getSqlDate(String key) {
Object value = get(key); return castToSqlDate(value);
} public java.sql.Timestamp getTimestamp(String key) {
Object value = get(key); return castToTimestamp(value);
} public Object put(String key, Object value) {
return map.put(key, value);
} public void putAll(Map<? extends String, ? extends Object> m) {
map.putAll(m);
} public void clear() {
map.clear();
} public Object remove(Object key) {
return map.remove(key);
} public Set<String> keySet() {
return map.keySet();
} public Collection<Object> values() {
return map.values();
} public Set<Map.Entry<String, Object>> entrySet() {
return map.entrySet();
} @Override
public Object clone() {
return new JSONObject(new HashMap<String, Object>(map));
} public boolean equals(Object obj) {
return this.map.equals(obj);
} public int hashCode() {
return this.map.hashCode();
} public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Class<?>[] parameterTypes = method.getParameterTypes();
if (parameterTypes.length == ) {
if (method.getName().equals("equals")) {
return this.equals(args[]);
} Class<?> returnType = method.getReturnType();
if (returnType != void.class) {
throw new JSONException("illegal setter");
} String name = null;
JSONField annotation = method.getAnnotation(JSONField.class);
if (annotation != null) {
if (annotation.name().length() != ) {
name = annotation.name();
}
} if (name == null) {
name = method.getName(); if (!name.startsWith("set")) {
throw new JSONException("illegal setter");
} name = name.substring();
if (name.length() == ) {
throw new JSONException("illegal setter");
}
name = Character.toLowerCase(name.charAt()) + name.substring();
} map.put(name, args[]);
return null;
} if (parameterTypes.length == ) {
Class<?> returnType = method.getReturnType();
if (returnType == void.class) {
throw new JSONException("illegal getter");
} String name = null;
JSONField annotation = method.getAnnotation(JSONField.class);
if (annotation != null) {
if (annotation.name().length() != ) {
name = annotation.name();
}
} if (name == null) {
name = method.getName();
if (name.startsWith("get")) {
name = name.substring();
if (name.length() == ) {
throw new JSONException("illegal getter");
}
name = Character.toLowerCase(name.charAt()) + name.substring();
} else if (name.startsWith("is")) {
name = name.substring();
if (name.length() == ) {
throw new JSONException("illegal getter");
}
name = Character.toLowerCase(name.charAt()) + name.substring();
} else if (name.startsWith("hashCode")) {
return this.hashCode();
} else if (name.startsWith("toString")) {
return this.toString();
} else {
throw new JSONException("illegal getter");
}
} Object value = map.get(name);
return TypeUtils.cast(value, method.getGenericReturnType(), ParserConfig.getGlobalInstance());
} throw new UnsupportedOperationException(method.toGenericString());
}
}
用法:直接将对象放入就能放回json对象了
1)json创建自定义对象
var p={id:1,name:"爸爸",sal:8000};
2).json创建对象集合
var ps=[{id:1,name:"呵呵"},{id:2,name:"呵呵1"},{id:3,name:"呵呵3"},];
3.创建一个对象,其中一个属性是数组
var p = {id:1,name:'哈哈',isLove:true,home:['广州','深圳'],show : function(str){alert("你是" + str);}};
4.json创建三级联动json+struts
链接:http://pan.baidu.com/s/1nvQEVCd 密码:5n5g
需要注意的地方:需要引入包
struts2-json-plugin-2.3.1.1.jar
使用第三方工具,将JavaBean对象/List或Set或Map对象转成JSON
》commons-beanutils-1.7.0.jar
》commons-collections-3.1.jar
》commons-lang-2.5.jar
》commons-logging-1.1.1.jar
》ezmorph-1.0.3.jar
》json-lib-2.1-jdk15.jar
各自公用
(1)JavaBean----->JSON
》JSONArray jsonArray = JSONArray.fromObject(city);
》String jsonJAVA = jsonArray.toString();
(2)List<JavaBean>----->JSON
》JSONArray jsonArray = JSONArray.fromObject(cityList);
》String jsonJAVA = jsonArray.toString();
(3)List<String>----->JSON
》JSONArray jsonArray = JSONArray.fromObject(stringList);
》String jsonJAVA = jsonArray.toString();
(4)Set<JavaBean>----->JSON
》JSONArray jsonArray = JSONArray.fromObject(citySet);
》String jsonJAVA = jsonArray.toString();
(5)Map<String,Object>----->JSON
》JSONArray jsonArray = JSONArray.fromObject(map);
》String jsonJAVA = jsonArray.toString();
最后一个例子切记,将来jQuery-EasyUI-DataGrid组件时我们还要用到
将来,在企业中,就算脱离struts2的环境,也能用第三方工具,将Java类型转成JSON文本
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <package name="myPackage" extends="json-default" namespace="/"> <!-- 全局结果类型 -->
<global-results>
<result name="success" type="json"/>
</global-results> <action
name="checkRequest"
class="cn.itcast.javaee.js.checkcode.CheckcodeAction"
method="check">
</action> <!-- 省份->城市 -->
<action
name="findCityByProvinceRequest"
class="cn.itcast.javaee.js.provincecityarea.ProvinceCityAreaAction"
method="findCityByProvince">
</action> <!-- 城市->区域 -->
<action
name="findAreaByCityRequest"
class="cn.itcast.javaee.js.provincecityarea.ProvinceCityAreaAction"
method="findAreaByCity">
</action> </package> </struts>
provinceCityArea.jsp
//provinceCityArea.jsp <%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>省份-城市-区域三级联动【Struts2 + JSON版】</title>
<script type="text/javascript" src="js/ajax.js"></script>
</head>
<body> <select id="provinceID" style="width:111px">
<option>选择省份</option>
<option>湖北</option>
<option>湖南</option>
<option>广东</option>
</select> <select id="cityID" style="width:111px">
<option>选择城市</option>
</select> <select id="areaID" style="width:111px">
<option>选择区域</option>
</select> <!-- 省份->城市 -->
<script type="text/javascript">
document.getElementById("provinceID").onchange = function(){
//清空城市下拉框
var cityElement = document.getElementById("cityID");
cityElement.options.length = 1;
//清空区域下拉框
var areaElement = document.getElementById("areaID");
areaElement.options.length = 1; var province = this[this.selectedIndex].innerHTML;
if("选择省份" != province){
//NO1)
var ajax = createAJAX();
//NO2)
var method = "POST";
var url = "${pageContext.request.contextPath}/findCityByProvinceRequest?time="+new Date().getTime();
ajax.open(method,url);
//NO3)
ajax.setRequestHeader("content-type","application/x-www-form-urlencoded")
//NO4)
var content = "bean.province=" + province;
ajax.send(content); //-------------------------------------------等待 //NO5
ajax.onreadystatechange = function(){
if(ajax.readyState == 4){
if(ajax.status == 200){
//NO6)返回JAVA格式的JSON文本
var jsonJAVA = ajax.responseText; //p所代表的是java格式的json文本,是不能直接被js执行的
//解决方案:将java格式的json文本,转成js格式的json文本
//如何做:用js提供的一个函数搞定
var jsonJS = eval("("+jsonJAVA+")"); var array = jsonJS.cityList;
var size = array.length;
for(var i=0;i<size;i++){
var city = array[i];
var option = document.createElement("option");
option.innerHTML = city;
cityElement.appendChild(option);
}
}
}
}
}
}
</script> <!-- 城市->区域 -->
<script type="text/javascript">
document.getElementById("cityID").onchange = function(){
var areaElement = document.getElementById("areaID");
areaElement.options.length = 1;
var city = this[this.selectedIndex].innerHTML;
if("选择城市" != city){
//NO1)
var ajax = createAJAX();
//NO2)
var method = "POST";
var url = "${pageContext.request.contextPath}/findAreaByCityRequest?time="+new Date().getTime();
ajax.open(method,url);
//NO3)
ajax.setRequestHeader("content-type","application/x-www-form-urlencoded")
//NO4)
var content = "bean.city=" + city;
ajax.send(content); //------------------------------------------等待 //NO5)
ajax.onreadystatechange = function(){ if(ajax.readyState == 4){
if(ajax.status == 200){
//NO6)
var jsonJAVA = ajax.responseText;
var jsonJS = eval("("+jsonJAVA+")");
var array = jsonJS.areaList;
var size = array.length;
for(var i=0;i<size;i++){
var area = array[i];
var option = document.createElement("option");
option.innerHTML = area;
areaElement.appendChild(option);
}
}
}
} }
}
</script> </body>
</html>
action
package cn.itcast.javaee.js.provincecityarea; import java.util.ArrayList;
import java.util.List; import com.opensymphony.xwork2.ActionSupport; /**
* 省份-城市-区域三级联动【Struts2 + JSON版】
* @author AdminTC
*/
public class ProvinceCityAreaAction extends ActionSupport{
/**
*
*/
private static final long serialVersionUID = 1L;
private Bean bean;
public Bean getBean() {
return bean;
}
public void setBean(Bean bean) {
this.bean = bean;
}
/**
* 根据省份获取城市
*/
public String findCityByProvince() throws Exception {
cityList = new ArrayList<String>();
if("湖北".equals(bean.getProvince())){
cityList.add("武汉");
cityList.add("赤壁");
}else if("湖南".equals(bean.getProvince())){
cityList.add("郴州");
cityList.add("张家界");
cityList.add("浏阳");
}else if("广东".equals(bean.getProvince())){
cityList.add("阳江");
cityList.add("清远");
cityList.add("佛山");
cityList.add("湛江");
}
//让struts2框架帮你将List/Set/Map<String>转成JSON文本
return SUCCESS;
} /**
* 根据城市获取区域
*/
public String findAreaByCity() throws Exception {
areaList = new ArrayList<String>();
if("阳江".equals(bean.getCity())){
areaList.add("AA");
areaList.add("BB");
}else if("清远".equals(bean.getCity())){
areaList.add("CC");
areaList.add("DD");;
}else if("佛山".equals(bean.getCity())){
areaList.add("EE");
areaList.add("FF");
}else if("湛江".equals(bean.getCity())){
areaList.add("GG");
areaList.add("HH");
}
return SUCCESS;
}
private List<String> areaList;//区域的集合
private List<String> cityList;//城市的集合
public List<String> getCityList() {
return cityList;
}
public List<String> getAreaList() {
return areaList;
} }
4.例子:js例子
验证码:image.jsp
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ page contentType="image/jpeg" import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*" %>
<%!
public Color getColor(){
Random random = new Random();
int r = random.nextInt(256);//0-255
int g = random.nextInt(256);
int b = random.nextInt(256);
return new Color(r,g,b);
}
public String getNum(){
String str = "";
Random random = new Random();
for(int i=0;i<4;i++){
str += random.nextInt(10);//0-9
}
return str;
}
%>
<%
response.setHeader("pragma", "mo-cache");
response.setHeader("cache-control", "no-cache");
response.setDateHeader("expires", 0); BufferedImage image = new BufferedImage(80,30,BufferedImage.TYPE_INT_RGB); Graphics g = image.getGraphics();
g.setColor(new Color(200,200,200));
g.fillRect(0,0,80,30); for (int i = 0; i < 30; i++) {
Random random = new Random();
int x = random.nextInt(80);
int y = random.nextInt(30);
int xl = random.nextInt(x+10);
int yl = random.nextInt(y+10);
g.setColor(getColor());
g.drawLine(x, y, x + xl, y + yl);
} g.setFont(new Font("serif", Font.BOLD,16));
g.setColor(Color.BLACK);
String checkNum = getNum();//"2525" StringBuffer sb = new StringBuffer();
for(int i=0;i<checkNum.length();i++){
sb.append(checkNum.charAt(i)+" ");//"2 5 2 5"
}
g.drawString(sb.toString(),15,20); session.setAttribute("CHECKNUM",checkNum);// ImageIO.write(image,"jpeg",response.getOutputStream());
out.clear();
out = pageContext.pushBody();
%>
jsp使用这个验证码的例子:
<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>验证码检查</title>
<script type="text/javascript" src="js/ajax.js"></script>
</head>
<body> <form>
<table border="0" align="center">
<tr>
<th>验证码:</th>
<td><input size="2" type="text" name="checkcode" id="checkcodeID" maxlength="4"/></td>
<td><img src="01_image.jsp"/>
<td id="res"></td>
</tr>
</table>
</form> <script type="text/javascript">
//去掉二边的空格
function trim(str){" zhaojun "
str = str.replace(/^\s*/,"");//"zhaojun "
str = str.replace(/\s*$/,"");//"zhaojun"
return str;
}
</script> <script type="text/javascript">
document.getElementById("checkcodeID").onkeyup = function(){
var checkcode = this.value;
checkcode = trim(checkcode);//
if(checkcode.length == 4){
//NO1)
var ajax = createAJAX();
//NO2)
var method = "POST";
var url = "${pageContext.request.contextPath}/checkRequest?time="+new Date().getTime();
ajax.open(method,url);
//NO3)
ajax.setRequestHeader("content-type","application/x-www-form-urlencoded");
//NO4)
var content = "checkcode=" + checkcode;
ajax.send(content); //--------------------------------------------------------等待 //NO5)
ajax.onreadystatechange = function(){
if(ajax.readyState == 4){
if(ajax.status == 200){
//NO6)
var tip = ajax.responseText; //NO7)
var img = document.createElement("img");
img.src = tip;
img.style.width = "14px";
img.style.height = "14px";
var td = document.getElementById("res");
td.innerHTML = "";
td.appendChild(img);
}
}
}
}else{
//清空图片
var td = document.getElementById("res");
td.innerHTML = "";
}
}
</script> </body>
</html> action:
package cn.itcast.javaee.js.checkcode; import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport; /**
* 验证码检查
* @author AdminTC
*/
public class CheckcodeAction extends ActionSupport{
//客户端验证码
private String checkcode;//2525
//注入客户端验证码
public void setCheckcode(String checkcode) {
this.checkcode = checkcode;
}
/**
* 验证
*/
public String check() throws Exception {
//图片路径
String tip = "images/MsgError.gif";
//从服务器获取session中的验证码
String checkcodeServer = (String) ActionContext.getContext().getSession().get("CHECKNUM");
//将客户端的验证码与服务端的验证码进行比较
if(checkcode.equals(checkcodeServer)){
tip = "images/MsgSent.gif";
}
//以IO流的方式将tip变量的值输出到AJAX异步对象中
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("text/html;charset=UTF-8");
PrintWriter pw = response.getWriter();
pw.write(tip);
pw.flush();
pw.close();
//以下方式不是最好的,但可以完成AJAX异步交互
return null;
}
}
创建ajax
//创建AJAX异步对象,即XMLHttpRequest
function createAJAX(){
var ajax = null;
try{
ajax = new ActiveXObject("microsoft.xmlhttp");
}catch(e1){
try{
ajax = new XMLHttpRequest();
}catch(e2){
alert("你的浏览器不支持ajax,请更换浏览器");
}
}
return ajax;
}
去String空白
function trim(str){
str=str.replace(/^\s*/,"");
str=str.replace(/\s*$/,"");
return str;
}
java深入探究13-js,ajax的更多相关文章
- Atitit. 数据约束 校验 原理理论与 架构设计 理念模式java php c#.net js javascript mysql oracle
Atitit. 数据约束 校验 原理理论与 架构设计 理念模式java php c#.net js javascript mysql oracle 1. 主键1 2. uniq index2 3. ...
- encodeURIComponent编码后java后台的解码 (AJAX中文解决方案)
encodeURIComponent编码后java后台的解码 (AJAX中文解决方案) 同学的毕业设计出现JavaScript用encodeURIComponentt编码后无法再后台解码的问题. 原来 ...
- JavaScript学习总结【12】、JS AJAX应用
1.AJAX 简介 AJAX(音译为:阿贾克斯) = Asynchronous JavaScript and XML(异步的 JavaScript 和 XML),是指一种创建交互式网页应用的网页开发技 ...
- Atitit.异步编程 java .net php python js 对照
Atitit.异步编程 java .net php python js 的比較 1. 1.异步任务,异步模式, APM模式,, EAP模式, TAP 1 1.1. APM模式: Beg ...
- java后台获取和js拼接展示信息
java后台获取和js拼接展示信息: html页面代码: <div class="results-bd"> <table id="activityInf ...
- Atitit.异步编程 java .net php python js 的比较
Atitit.异步编程 java .net php python js 的比较 1. 1.异步任务,异步模式, APM模式,, EAP模式, TAP 1 1.1. APM模式: Beg ...
- Java程序员之JS(一) 入门
背景:使用了JS做一个 WEB 项目之后,一直有使用JS 的一个功能,突然某一天项目重新规划,开始自己手动写一些原始JS,情况不妙,原来之前一直是用同事搭建好的框架在开发,对 JS 零基础的我一直在 ...
- atitit.跨语言实现备份mysql数据库 为sql文件特性 api 兼容性java c#.net php js
atitit.跨语言实现备份mysql数据库 为sql文件特性 api 兼容性java c#.net php js 1. 两个方法:: bat vs mysqldump(推荐) vs lang ...
- Atitit 文件上传 架构设计 实现机制 解决方案 实践java php c#.net js javascript c++ python
Atitit 文件上传 架构设计 实现机制 解决方案 实践java php c#.net js javascript c++ python 1. 上传的几点要求2 1.1. 本地预览2 1.2 ...
随机推荐
- python3 - property的使用
传统的绑定属性值,会把属性暴露出去,而且无法检查参数是否合法,如下: class Test(object): def __int__(self,age): self.age = age 为了检查参数 ...
- Java数据类型的转换:隐式(自动)转换与强制转换
原文链接:http://java.chinaitlab.com/base/725590.html 一些初学JAVA的朋友可能会遇到JAVA的数据类型之间转换的苦恼,例如,整数和float,double ...
- this.$apply()
chooseVideo(e) { this.fileInfo = {} let that = this wx.chooseVideo({ sourceType: ['album', 'camera'] ...
- python系列六:Python3元组tuple
'''元组与列表类似,不同之处在于元组的元素不能修改.元组使用小括号,列表使用方括号.''''''uple元素不可变有一种特殊情况,当元素是可变对象时.对象内部属性是可以修改的!tuple的不可变限制 ...
- HashMap 扩容机制
引用于: http://www.cnblogs.com/hongdada/p/6024832.html HashMap: public HashMap(int initialCapacity, flo ...
- python函数回顾:setattr()
描述 setattr 函数对应函数 getatt(),用于设置属性值,该属性必须存在. 语法 setattr 语法: setattr(object, name, value) 参数 object -- ...
- atoi函数的一种实现
atoi函数的使用实例:[Ubuntu环境] main.c: #include <stdio.h> #include <stdlib.h> extern int factori ...
- JAVA抠取Excel中的图片
EXCEL中扔了一堆的图片,老大让对应到数据库中的数据上.思路先把图片抠出存成单个图片.然后上传到服务器,取下路径更新到数据库中. 注释掉的部分为有多个Excel时使用. package com.** ...
- Python 4 函数的参数,内置函数,装饰器,生成器,迭代器,
一.函数的参数: 1.位置参数:调用函数时根据函数定义的参数位置来传递参数. 2.关键字参数:用于函数调用,通过“键-值”形式加以指定.可以让函数更加清晰.容易使用,同时也清除了参数的顺序需求. 3. ...
- api响应类
接口开发响应类封装 class response{ /* * 封通信接口数据 * @param integer $code 状态码 * @param string $message 状态信息 * @p ...