自我学习总结1:ajax实现编辑框的验证

来源:互联网 发布:java过滤器的生命周期 编辑:程序博客网 时间:2024/05/16 01:46

<span style="font-family: Arial, Helvetica, sans-serif;"></span><p>目的就是在一个文本框中最多输入6个字符,实现的方法其实还有其他的,但是这里使用ajax实现</p><p>这个是一个.jsp中的代码,有javascript和html的代码</p>
<span style="font-family: Arial, Helvetica, sans-serif;"><%@ page language="java" contentType="text/html; charset=utf-8"</span>
    pageEncoding="utf-8"%><!DOCTYPE> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> <title>ajax测试</title> <script type="text/javascript">function ajaxFunction() { var xmlHttp; var str=document.getElementById("text1").value; try    {   // Firefox, Opera 8.0+, Safari    xmlHttp=new XMLHttpRequest();    } catch (e)    {  // Internet Explorer   try      {      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");      }   catch (e)      {      try         {         xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");         }      catch (e)         {         alert("您的浏览器不支持AJAX!");         return false;         }      }    } xmlHttp.onreadystatechange=function() { if(xmlHttp.readyState==4&&xmlHttp.status==200)   {   document.getElementById("p1").innerHTML=xmlHttp.responseText;   } } xmlHttp.open("GET","jsp2.jsp?t="+ Math.random()+"&action="+str,true); xmlHttp.send(null); }</script></head><body><input type="text" id="text1" onkeyup="ajaxFunction()"></input><p><span id="p1"></span></p></body></html>

这个是另一个.jsp中的代码,放的是jsp的代码

<%@ page language="java" contentType="text/html; charset=utf-8"    pageEncoding="utf-8"%><%String action="";try{action = request.getParameter("action"); if(action.length()>6){System.out.print("长度不能超过6"); out.print("长度不能超过6");}}catch(Exception e){System.out.println("error"+action);}%>


为什么要放到两个文件中呢,因为放到一个文件中会因为

xmlHttp.open("GET","jsp2.jsp?t="+ Math.random()+"&action="+str,true);中指到本文件而再用一次javascript和html的代码

导致出现错误,像我的这部分代码,如果放在一个中就会出现出现第二个文本框的问题


当然也可以用json来编写,难度会小很多,可以直接去看w3c的教程即可


0 0
原创粉丝点击