Ajax技術

1按鈕 2010-11-7 author:heguikun

<input type="text" name="petInfo.petName" value="晴天大聖" οnblur="return checkPetExists(this)">

2.腳本

<script type="text/javascript">
 //寵物名驗證並使用Ajax技術
 var xmlHttpRequest;//必須要設置全局變量,否則報對象未定義
 function createXmlHttpRequest()
 {
  if(window.ActiveXObject)
  {//IE瀏覽器
    xmlHttpRequest=new ActiveXObject("Microsoft.XMLHTTP");
  }
  else{//非IE瀏覽器
     xmlHttpRequest=new XMLHttpRequest();
  }
  return xmlHttpRequest;
 }
 function checkPetExists(oCtl)
 {
  var petName=oCtl.value;
  if(!petName)
  {
  alert("寵物名不能爲空!");
  oCtl.focus();
  return;
  }
  //請求字符串
  var url="pet.do?operate=doCheckUserExists&petName="+petName;
  //1.創建XMLHttpRequest組建
  var xmlHttpRequest=createXmlHttpRequest();
  //2.設置回調函數
  xmlHttpRequest.onreadystatechange=petaAjax;
  //3.初始化xmlHttpRequest組件
  xmlHttpRequest.open("GET",url,true);
  //發送請求
  xmlHttpRequest.send(null);
 }
 function  petaAjax()
 {
   if(xmlHttpRequest.readyState==4&&xmlHttpRequest.status==200)
    {
     var b=xmlHttpRequest.responseText;//獲取打印的只
       if(b=="true")
        {
          alert("該寵物名已被使用");
        }else
        {
          alert("該寵物名可用!");
        }
     }
 }

</script>

3.Action

 //ajax技術
 public ActionForward doCheckUserExists(ActionMapping mapping,
   ActionForm form, HttpServletRequest request,
   HttpServletResponse response) throws IOException {
  String petName = request.getParameter("petName");

  petName= new String(petName.getBytes("iso-8859-1"), "gbk");//iso-8859-1
  System.out.println(petName);
  List list=allBiz.query("from  PetInfo where petName='"+petName+"'");
  PrintWriter out=response.getWriter();
  if (list!=null&&list.size()>0) {
   out.write("true");//打印出來時爲了回調函數獲取這個字符串
  }else
  {
  out.write("false");
  }
  return null;
 }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章