1. 下载jquery.js文件及API
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>
<%
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>My JSP 'Test.jsp' starting page</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">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script type="text/javascript" src="<%=path%>/jslib/jquery-1.2.6.js"></script>
<script type="text/javascript">
function chkForm(){
//注意: jquery返回的 都是JQuery对象, 和js对象不一样,所以获得值等要调用jquery的方法来获得
var jQueryObj = $("#userName");
//获得值
var userName1 = $("#userName").val();
alert(userName1.length); //js的length会把中文的长度也认为1
alert('chkByteLen='+chkByteLength(userName1)); //一个中文两个字节
//$.trim("字符串") //去掉空格
var userName = encodeURI(encodeURI($("#userName").val()));
//alert(userName+""); //没有去除空格
//发送ajax请求
// $.post("ajaxServlet","userName="+userName,showAjaxResponse);
$.ajax({
type: "GET", //http请求方式POST
url: "ajaxServlet", //服务器段url地址
data: "userName=" + userName, //发送给服务器段的数据
dataType: "html", //告诉JQuery返回的数据格式xml
success: showAjaxResponse //定义交互完成,并且服务器正确返回数据时调用的回调函数
});
}
function showAjaxResponse(data){
var resultDivObj = $("#resultDiv");
resultDivObj.html(data);
}
function chkByteLength(str) {
if (str == null) return false;
var l = str.length;
var blen = 0;
for(i=0; i<l; i++) {
if ((str.charCodeAt(i) & 0xff00) != 0) {
blen ++;
}
blen ++;
}
return blen;
}
</script>
</head>
<body>
<form name="form1" action="TestOk.jsp" method="post">
<input type="text" id="userName" name="userName" οnblur="chkForm()" />
<input name="btn" type="button" value="校验" οnclick="chkForm()" />
</form>
<div id="resultDiv"></div>
</body>
</html>