欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Ajax 局部刷新

程序员文章站 2022-06-17 11:51:07
...

通过button按钮刷新页面数据:

1.前台配置jsp和js:

1.1 在<head>标签之前添加

<%
   String path = request.getContextPath();
%>

 1.2 添加应用访问路径

<script type="text/javascript">
        var appPath = '<%=path%>';
</script>

 1.3 <body>标签内容

<p>Welcome to the site <b id='boldStuff'>dude</b> </p> 
<input type='button' onclick='getInfo()' value='Change Text'/>

 1.4 js方法

//struts request
function getInfo()
  {
      var xhr = getXHR();
      xhr.open("POST", appPath+"/queryAction.do?method=getPageDetailInfo", true);
      alert(appPath);
      xhr.onreadystatechange = function() 
      {
          if (xhr.readyState == 4) 
          { 
              var empInfo = xhr.responseText;
              changeText(empInfo);
          }
      }
      xhr.send();
  }
//ajax request
 function getXHR()
  {
      try
      {
           return new XMLHttpRequest();
      }
      catch(e)
      {
          try
          {
              return new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch(e)
      {
          return new ActiveXObject("Msxml2.XMLHTTP");
          }
      }
  }
//change data
function changeText(html){
	var html = '<table><tr><td>123</td><td>456</td></tr><tr><td>789</td><td>0000</td></tr></table>';
	document.getElementById('boldStuff').innerHTML = html;
}


 2.后台数据响应

/**
     * 
     * {ajax局部数据请求}
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @author:王传对 [email protected]
     * @throws IOException 
     */
    public ActionForward getPageDetailInfo(ActionMapping mapping,ActionForm form,HttpServletRequest request,
            HttpServletResponse response) throws IOException{
        String resultHTMLString = "<table border=\"1\">";
        for(int i = 0;i<3;i++){
            resultHTMLString += "<tr><td>"+1+"</td><td>"+2+"</td></tr>";
        }
        resultHTMLString += "</table>";
        JSONObject obj = new JSONObject();  
        obj.put("resultHTMLString1", resultHTMLString);
        obj.put("resultHTMLString2", resultHTMLString);
        response.getWriter().write(obj.toString());  
        return null;
    }

 3.Struts相关配置

<action type="**.QueryAction" 
     parameter="method" 
     scope="request" 
     path="/queryAction" 
     name="qeuryForm">
<forward name="success" path="/**.jsp" />
<forward name="fail" path="/**.jsp" />
</action>

   最后在web.xml加载struts配置,启动工程,效果如下:

  Onclick之前:
Ajax 局部刷新

Onclick之后:
Ajax 局部刷新