日期:2014-05-16  浏览次数:20600 次

AJAX简单百度效果
<script type="text/javascript">
function createXmlHttpRequest()
{
var xmlHttp=null;
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}catch(se){
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
xmlHttp=new XMLHttpRequest();
}
}
if(xmlHttp==null){
alert("无法创建XMLHttpRequest");
}
return xmlHttp;
}

function login()
{
var xmlHttp=createXmlHttpRequest();
var uname=document.myform.username.value;
var pwd=document.myform.pwd.value;
//当请求状态改变
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4 && xmlHttp.status==200){
//接收响应文本
var txt=xmlHttp.responseText;
if(txt=="true"){
document.getElementById("msg").innerHTML="<a href='javascript:'>退出</a>";
}else{
alert("用户名或密码错误!请重新登录!");
document.getElementById("msg").innerHTML="<form action='' name='myform'>用户名:<input type='text' name='username' />密码:<input type='password' name='pwd'/><input type='button' onclick='login()' value='登录'/><br></form>";
}
}
};
//发送
xmlHttp.open("post","LoginServlet",true);
xmlHttp.setRequestHeader("content-type","application/x-www-form-urlencoded");
xmlHttp.send("username="+uname+"&pwd="+pwd);
}
String.prototype.trim=function(){
var reg=this.match(/^\s*(\S+(\s+\S+)*)\s*$/);
return reg!=null?reg[1]:"";
};
function show(){
var keyword=document.getElementById("keyword").value;
if(keyword.trim()==""){
return;
}
var xmlHttp=createXmlHttpRequest();
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4 && xmlHttp.status==200){
var txt=xmlHttp.responseText;
//alert(txt);
//var all=txt.split(",");
//alert(all.length);
document.getElementById("content").innerHTML=txt;
}
};
xmlHttp.open("get","SearchServlet?keyword="+keyword,true);
xmlHttp.send(null);
}
</script>
  </head>
 
  <body>
  <div id="msg">
    <form action="" name="myform">
用户名:
<input type="text" name="username" />
密码:<input type="password" name="pwd"/>
<input type="button" onclick="login()" value="登录"/>
<br>
</form>
</div>

baidu:<input type="text" id="keyword" onkeyup="show()" autocomplete="off" name="keyword" /><input type="button" onclick="show()" value="百度一下"/>
<div id="content" style="border:1px solid #ccc;width:300px;margin-left:33px;">
sdfljd
</div>


//servlelt类中处理页面的请求
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html;charset=gbk");
request.setCharacterEncoding("gbk");
String keyword=request.getParameter("keyword");
keyword=new String(keyword.getBytes("iso-8859-1"),"gbk");

NewsDaoImpl nd=new NewsDaoImpl();
List<String> list=nd.getALL(keyword);
PrintWriter out = response.getWriter();
for(String key:list){
out.print("<div onmouseout=\"this.style.backgroundColor=''\" onmouseover=\"this.style.backgroundColor='blue';document.getElementById('keyword').value='"+key+"';\">"+key+"</div>");
}