javascript学习笔记一

来源:互联网 发布:数据回溯是什么意思 编辑:程序博客网 时间:2024/06/05 17:32

现在正在学JavaScript,也做了一些简单的测试,在此记录一下

下面这段代码是一个简单的采用面向对象编写的js类,也就是是个Ajax

 

js代码

Ajax = function() {
 var xmlhttp = false; 

 var responsemsg = "";
 // 创建XMLHttpRequest对象,并赋值给变量xmlHttp
 // 该方法为一公有实例方法
 var createXmlhttp = function() {
  try {
   xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
  } catch (e) {
   try {
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
   } catch (e1) {
    xmlhttp = false;
   }
  }
  if (!xmlhttp && typeof (XMLHttpRequest) != "Undefined") {

   xmlhttp = new XMLHttpRequest();
  }
 } ;

 // 在执行交互过程中状态的改变
 var createConn = function() {
//  window.alert("readyState:"+xmlhttp.readyState) ;
  if (xmlhttp.readyState != 4) {
   beforeConnectionSuc();
  } else {
   afterConnectionSuc();
  }
 } ;

 function beforeConnectionSuc() {
//  window.alert("aaa");
 }

 function afterConnectionSuc() {
  responsemsg = xmlhttp.responseText;
//  window.alert(responsemsg);
  document.getElementById("result").innerHTML = responsemsg;
 }

 // 接口,用于服务器与客户端的交互
 this.interactive = function(urlpath) {
  createXmlhttp() ;
  xmlhttp.open("post", urlpath, true);
  xmlhttp.onreadystatechange = createConn ; //今天就在这栽了跟头,
  xmlhttp.send("");
 };

} ;

 

 

页面代码

<html>
 <head>
  <title>My JSP 'MyJsp.jsp' starting page</title>
  <script type="text/javascript" src="clazz.js"></script>
  <script type="text/javascript">
  function callfun(urlpath){
   var ajax = new Ajax() ;
   ajax.interactive(paras) ;
   var login = document.getElementById("login") ;
   login.style.display = "none" ;
  }
  </script>
 </head>

 <body>
  <div id="login">
   <form action="/ajaxTest/pages" method="post">
    用户登入
    <br />
    <p />
     用户名:
     <input type="text" name="username" value="" id="username"/>
     <br />
    <p />
     密&nbsp;&nbsp;&nbsp;码:
     <input type="password" name="pwd" value="" />
    <p />
     &nbsp;&nbsp;&nbsp;&nbsp;
     <input type="button" value="登入"
      onclick="javascript:callfun('/ajaxTest/pages')" />
     &nbsp;&nbsp;&nbsp;&nbsp;
     <input type="button" value="注册" />
   </form>
  </div>
  <div id="result" ></div>
 </body>
</html>

 

这里采用了古老的HttpServlet,这是代码的一部分

response.setContentType("text/html;charset=utf-8");  
  try {
   PrintWriter write = response.getWriter() ;
   write.println("<input type='button' value='GO'/>") ;
   write.flush() ;
  } catch (IOException e) {
   e.printStackTrace();

  }

 

这里我用firefox浏览器测试是没问题的,对IE浏览器报出错误,'Ajax'未定义

原创粉丝点击