prototype.js学习笔记

1.下载prototype.js文件,并放入到项目中

2、index.jsp文件(例子)

<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>测试prototype.js</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<script type="text/javascript" src="<%=path%>/script/prototype.js"></script>
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script type="text/javascript">
//检测邮箱
function chkEmail(str){ //是邮箱地址返回true,不是邮箱地址返回false
var reg=/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
return reg.test(str);
}

//使用正则表达式截取空格
function trim(s){
//先去掉字符串前面的空格,再去掉字符串后面的空格
return s.replace(/^\s*/,"").replace(/\s*$/,"");
}

function chkForm(){

// alert(trim(Form.Element.serialize("email")));
Element.hide("hid"); //隐藏层
return false;
}

function chgDiv(){ //隐藏转换
if($("hid").style.display=="none"){
Element.show("hid"); //展开层
}else{
Element.hide("hid"); //隐藏层
}
}
//获得值
function getValue(){
alert("获得userName的值="+trim(Form.Element.getValue("userName"))); //获得userName的值,也可用$("userName").value
}

//ajax使用
function sendAjax(){
//请求的地址(url也可有参数,如url='do_ajax.jsp?userPwd=111' 或 url='ajaxAction.do?method=add')
var url = '<%=path%>/script/do_ajax.jsp?userPwd=111';
//请求参数(params可加上这个参数以清除缓存"&nocache="+ new Date().getTime())
var params = "userName="+$("userName").value;
//创建Ajax.Request对象,对应于发送请求
var myAjax = new Ajax.Request(
url,
{
//请求方法,注意这里只能是小写的,不能是大写的
method: 'post',
//请求参数
parameters: params,
//指定回调函数
onComplete: showResponse,
//是否异步发送请求
asynchronous: true
}
); //myAjax

}
//定义回调函数
function showResponse(originalRequest){
alert(originalRequest.responseText);
}
</script>
</head>

<body>
<form action="" name="form1">
Email: <input type="text" name="email" id="email" />
<input type="button" name="btn" value="确定" onclick="chkForm()" />
</form>

<input type="button" name="btn2" value="隐藏转换" onclick="chgDiv()">
<div id="hid" >我要被隐藏了!</div>

<input type="text" id="userName" name="userName" value="userNameValue">
<input type="button" name="btn3" value="返回userName的值" onclick="getValue()">

<input type="button" name="btn4" value="发送ajax请求" onclick="sendAjax()">
</body>
</html>

3、do_ajax.jsp文件

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String str = request.getParameter("userName");
System.out.println(str);

String userPwd = request.getParameter("userPwd");
System.out.println("userPwd="+userPwd);
out.print("ajax success,成功!");
%>

你可能感兴趣的:(JavaScript,jsp,Ajax,正则表达式,prototype)