六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 41|回复: 0

ajax + servlet实现页面局部刷新

[复制链接]

升级  36%

2

主题

2

主题

2

主题

童生

Rank: 1

积分
18
 楼主| 发表于 2013-1-29 11:45:08 | 显示全部楼层 |阅读模式
jsp页面部分代码:
<form  name="myForm" method="get">  
      <input type="text" name="input1" />
      <input type="button" value="Click"  />  
      <input type="text" name="output1" />
</form>


ajaxFunction所在的js代码,其中就有ajax的内容:
function ajaxFunction()
{

var xmlHttp;

try
    {
   // Firefox, Opera 8.0+, Safari
    xmlHttp=new XMLHttpRequest();
    }
catch (e)
    {

  // Internet Explorer
   try
      {
      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
      }
   catch (e)
      {

      try
         {
         xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
         }
      catch (e)
         {
         alert("您的浏览器不支持AJAX!");
         return false;
         }
      }
    }

    url="output.action?salt"+new Date();
     xmlHttp.open("get",url,false);
    xmlHttp.onreadystatechange=function()
    {
      if(xmlHttp.readyState==4)
        {  if(xmlHttp.status==200){
          document.myForm.output1.value=xmlHttp.responseText.toString();
           }
        }
      }
    xmlHttp.send();
}


action中的get方法:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("here is the get function");
PrintWriter out = response.getWriter();
response.setContentType("text/html");
String input1=request.getParameter("input1");
System.out.println(input1);
    if("mage".equalsIgnoreCase(input1)){
System.out.println("you have entered mage");   //不要怪我,我也是v大迷。
out.print("vurtne");
out.flush();
out.close();}else{
System.out.println("you have not entered mage");
out.print("drakedog"); //也不要怪我,我觉得dd打的也不错。
out.flush();
out.close();
}
}


web.xml配置内容:
<servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>OutputAction</servlet-name>
    <servlet-class>com.test.action.OutputAction</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>OutputAction</servlet-name>
    <url-pattern>*.action</url-pattern>
  </servlet-mapping>
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表