最原始的ajax实现前台验证
<script type="text/javascript">
var request;
function createRequest(){
try{
request=new XMLHttpRequest();
}catch(trymicrosoft){
try{
request=new ActiveXobject("Msxml2.XMLHTTP");
}catch(othermicrosoft){
try{
request=new ActiveXobject("Microsoft.XMLHTTP");
}catch(failed){
request=false;
}
}
}
if(!request)
alert("Error initializing XMLHttpRequest!");
}
function getCustomerInfo(){
createRequest();
var modelsName=document.getElementById("CDictionaryName").value;
while ((modelsName.indexOf(" ")==0) && (modelsName.length>1)){
modelsName=modelsName.substring(1,modelsName.length);
}//去除前面空格
while ((modelsName.lastIndexOf(" ")==modelsName.length-1)&&(modelsName.length>1)){
modelsName=modelsName.substring(0,modelsName.length-1);
}//去除后面空格
if (modelsName==" "){
modelsName="";
}
var url="<%=basePath%>models.do?method=selectModelsByName&modelsName="+modelsName;
url=encodeURI(url);
url=encodeURI(url); //写一个不行。如果写一个就是????号。
//写2个,则输出 %df%a4这中.
request.open("GET",url,true);
request.onreadystatechange=updatePage;
request.send(null);
}
function updatePage(){
if(request.readyState==4)
{
if(request.status==200)
{
var modelsName=document.getElementById("CDictionaryName");
var responseText=request.responseText;
if(responseText=="车型已存在"){
modelsName.value="";
modelsName.focus();
document.getElementById("mName").innerHTML=responseText+"!请重新换个名字!";
}else{
document.getElementById("mName").innerHTML=responseText
}
}
else if (request.status==404)
{
modelsName.value="";
alert("Request URL does not exist");
}else{
alert(modelsName.value);
modelsName.value ="";
alert("Error:status code is "+ request.status);
}
}
}
</script>
<script type="text/javascript">
function sub(){
var mName=document.getElementById("CDictionaryName");
if(mName.value==""){
document.getElementById("mName").innerHTML="对不起!车型不能为空!";
return false;
}else{
return true;
}
}
</script>
后台Action代码:
// 根据ID查看
public ActionForward selectModelsByName(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) {
String cIictionaryName = request.getParameter("modelsName");
try {
cIictionaryName = java.net.URLDecoder.decode(cIictionaryName,"UTF-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} //这句话一定要,因为如果不写的 //话,编码 就 是%E5%A6%88%System.out
System.out.println(cIictionaryName+"aaaaaaaa");
//response.setContentType(arg0)
try {
response.setContentType("text/html;charset=utf-8");
PrintWriter out=response.getWriter();
Dictionary dictionary=new Dictionary();
dictionary.setCDictionaryFlag("1");
dictionary.setCDictionaryName(cIictionaryName);
List<Dictionary> reList=dictionaryService.findByExample(dictionary);
if(reList.size()>0){
out.print("车型已存在");
}else {
out.print("该车型可以使用!");
}
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}