写的第一个ajax实例,结合jquery

作者在 2010-07-12 11:15:57 发布以下内容
新建一个html文件如
<html>
  <head>
    <title>ajax.html</title>

  <script type="text/javascript" src="jqueryjs/values.js"></script>
  <script type="text/javascript" src="jqueryjs/jquery-1.4.2.js"></script></head>
  <body>
  这是一个ajax的程序
  请输入你的用户名:<input type="text" id="userName"/><div id="result"></div><br/>
  <input type="button" value="提交" onclick="valvatio()"/>
  </body>
</html>
上面jquery-1.4.2.js是库
在新建一个js文件
function valvatio(){
    var userObject=$("#userName");//得到表单
    var username=userObject.val();//得到表单的值
    $.get("servlet/ValiServlet?name="+username,null,callback);//将得到的值传到servlet中,
}
function callback(data){//返回的方法,注间其中的data是一定要要的
    var resultObj=$("#result");//得到div表单
    resultObj.html("<font color='red'>"+data+"</font>");//将得到的值写入div中
}
在servlet中写
response.setContentType("text/html;charset=gbk");
        PrintWriter out = response.getWriter();
        String name=request.getParameter("name");//这里的name是在js中的name
        if(name==null&&name.length()==0){
            out.println("用户不能为空");
        }
        else{
            if("yds".equals(name)){
                out.println("用户名已经存在了");
            }
            else{
                out.println("用户不存在");
            }
        }
    }
ajax | 阅读 1383 次
文章评论,共1条
wtuaimmmm(作者)
2010-07-12 14:10
1
var xmlhttp;<br />
function verify1(){<br />
 //实用xmlhttprequest的应用<br />
&nbsp; &nbsp; var name=document.getElementById(&quot;userName&quot;).value;&nbsp; &nbsp; //得到表单的值<br />
 //创建XMLHTTpRequest的对象<br />
&nbsp; &nbsp; if(window.XMLHttpRequest){<br />
&nbsp; &nbsp;&nbsp; &nbsp;&nbsp;&nbsp;xmlhttp=new XMLHttpRequest();<br />
&nbsp; &nbsp;&nbsp; &nbsp;&nbsp;&nbsp;if(xmlhttp.overrideMimeType){<br />
&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;xmlhttp.overrideMimeType(&quot;text/xml&quot;);<br />
&nbsp; &nbsp;&nbsp; &nbsp;&nbsp;&nbsp;}<br />
&nbsp; &nbsp; }<br />
&nbsp; &nbsp; else if(window.ActiveXObject()){<br />
&nbsp; &nbsp;&nbsp; &nbsp;&nbsp;&nbsp;xmlhttp=new ActiveXObject(&quot;Microsoft.XMLHTTP&quot;);<br />
&nbsp; &nbsp; }<br />
&nbsp; &nbsp;xmlhttp.onreadystatechange=callback;<br />
&nbsp; &nbsp; xmlhttp.open(&quot;GET&quot;,&quot;AjaxServlet?name=&quot;+name,true);<br />
&nbsp; &nbsp; xmlhttp.send(null);<br />
}<br />
function callback(){<br />
 if(xmlhttp.readyState==4){<br />
&nbsp; &nbsp;&nbsp;&nbsp;if(xmlhttp.status==200){<br />
&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;var responstText=xmlhttp.responseText;<br />
&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;var resultNode=document.getElementById(&quot;result&quot;);<br />
&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;resultNode.innerHTML=responstText;<br />
&nbsp; &nbsp;&nbsp;&nbsp;}<br />
 }<br />
}<br />
不用jquery来写的
游客请输入验证码
浏览274701次