声明:本文系JavaEye网站发布的原创博客文章,未经作者书面许可,严禁任何网站转载本文,否则必将追究法律责任!
首页代码如下 index.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>index.html</title>
<!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
<script type="text/javascript" src="js/index.js"></script>
</head>
<body>
<form action="/AjaxTest/Test">
<p><!-- 提交后的号码会发到servlet,然后显示在下面的div标签里面 -->
输入电话号码:
<input type="text" size="14" name="phone" id="phone"
onChange="getCustomerInfo();" />
</p>
<div id="address"></div>
<p>
下面会输出servlet里面的文字:
</p>
<p>
<textarea name="order" rows="6" cols="50" id="order"></textarea>
</p>
<p>
<input type="submit" value="提交" id="submit" />
</p>
</form>
</body>
</html>
index.js javascript文件
var request = false;
try
{// 根据浏览器的不同创建XMLHttpRequest对象
request = new XMLHttpRequest ();
} catch ( trymicrosoft )
{
try
{
request = new ActiveXObject ( "Msxml2.XMLHTTP" );
} catch ( othermicrosoft )
{
try
{
request = new ActiveXObject ( "Microsoft.XMLHTTP" );
} catch ( failed )
{
request = false;
}
}
}
if ( ! request )
alert ( "Error initializing XMLHttpRequest!" );
/**
* 在鼠标离开控件的时候在后台和服务器连接,异步提交
*/
function getCustomerInfo ()
{
var phone = document.getElementById ( "phone" ).value;
var url = "Test?phone=" + escape ( phone );// 请求地址
request.open ( "GET" , url , true );// 以GET方式请求url,true表示请求是异步的
request.onreadystatechange = updatePage;// 服务器返回成功后的回调函数
request.send ( null );
}
/**
* 服务器返回后调用的回调函数
*/
function updatePage ()
{
if ( request.readyState == 4 )
{
if ( request.status == 200 )
{// responseText得到返回文本字符串
var response = request.responseText.split ( "|" );
alert ( unescape ( response ) );
document.getElementById ( "order" ).value = response[0];
document.getElementById ( "address" ).innerHTML = response[1]
.replace ( /\n/g , "" );
} else
alert ( "status is " + request.status );
}
}
后台servlet文件:Test.java
package com.egt.ajax.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @Author 曹斌 Sep 6, 2008
* @Email
[email protected]
* @Blog www3.iteye.com
*
* @Description
*/
public class Test extends HttpServlet
{
public Test ()
{
super();
}
public void destroy ()
{
super.destroy();
}
public void doGet ( HttpServletRequest request ,
HttpServletResponse response ) throws ServletException ,
IOException
{
//这里要设置字符编码格式,否则GET方式要出现乱码。
response.setContentType("text/HTML;charset=GBK");
request.setCharacterEncoding("GBK");
response.setCharacterEncoding("GBK");
PrintWriter out = response.getWriter();
out.println("servlet里面的GET方法文字|"+request.getParameter("phone"));
out.flush();
out.close();
}
public void init () throws ServletException
{
}
}
已有 0 人发表留言,猛击->>这里<<-参与讨论
JavaEye推荐
搜狐网站诚聘Java、PHP和C++工程师
微软硬件工程大会报名五折优惠!
文章来源:http://www3.iteye.com/blog/237931