用AJAX的Get和Post调用Servlet的简单示例

来源:互联网 发布:球球大作战骂人软件 编辑:程序博客网 时间:2024/05/17 01:10

Servlet类的代码:

public class StbCfgServicetServlet  extends HttpServlet

{
    private static final Logger log = LoggerFactory.getLogger(StbCfgServicetServlet.class);
   
    public void service(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
    {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");  
        response.setHeader("Cache-Control","no-cache");  
        response.setStatus(response.SC_OK);
        response.setContentLength(1000);
        response.setHeader("Access-Control-Allow-Origin", "*");
        PrintWriter out = response.getWriter();
        out.print("aaabbbccc");
        log.info("[cfg update Servlet] is ok!");
        out.flush();  
        out.close();

    }

}



html页面代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ϟ±덢τµµ</title>
<script language="javascript">
    
var xmlHttp;

function createXMLHttpRequest()
{
     if(window.ActiveXObject)
     {
          xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
     }
     else if(window.XMLHttpRequest)
     {
          xmlHttp = new XMLHttpRequest();
     }
}
function createQueryString()
{
     var smcId = document.getElementById("smcId").value;
     var cfgVersion =document.getElementById("cfgVersion").value;
     var cfgInfo = document.getElementById("cfgInfo").value;
     var queryString = "smcId=" + smcId + "&cfgVersion=" + cfgVersion + "&cfgInfo=" + cfgInfo;
     
     return queryString;
}

function doRequestUsingGET()
{
     createXMLHttpRequest();
     var queryString = "http://ip:8080/apphaus-webapp/servlet/cfg?";
     //var queryString = "http://localhost:8080/struts-blank/cfg/CfgAction";
     //queryString = queryString + createQueryString();
     xmlHttp.onreadystatechange = handleStateChange;
     xmlHttp.open("GET", queryString, true);
     xmlHttp.send(null);
}

function doRequestUsingPost()
{
     createXMLHttpRequest();
     var URL = "http://ip:8080/apphaus-webapp/servlet/cfg";
     //var URL = "http://localhost:8080/struts-blank/cfg/ajax";
     var queryString = ""; //createQueryString();
     xmlHttp.open("POST", URL, true);
     xmlHttp.onreadystatechange = handleStateChange;
     xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
     xmlHttp.send(queryString);
}

function handleStateChange()
{
     if(xmlHttp.readyState == 4)
     {
          alert("======XMLHttpRequest.status=============" + xmlHttp.status)
          if(xmlHttp.status == 200 || xmlHttp.status == 0)
          {
               parseResults();
          }
     }
}

function parseResults()
{
     var responseDiv = document.getElementById("serverResponse");
     alert('responseDiv=' + responseDiv);
     alert('responseDiv.hasChildNodes()=' + responseDiv.hasChildNodes());
     if(responseDiv.hasChildNodes())
     {
             alert('in ------------------');
             responseDiv.removeChild(responseDiv.childNodes[0]);
     }
     alert('xmlHttp.responseText ======= ' + xmlHttp.responseText);
     alert('xmlHttp.responseXML ======= ' + xmlHttp.responseXML);
     var responseText = document.createTextNode(xmlHttp.responseText);
     responseDiv.appendChild(responseText);
}

</script>
</head>

<body>
<form id="form1" name="form1" method="post" action="#">
  <p><br />
    <br />
    smcId:<input name="smcId" type="text" id="smcId" />
</p>
  <p>
    <label>
    cfgVersion:<input type="text" name="cfgVersion" id="cfgVersion"  />
    </label>
</p>
  <p>
    cfgInfo:<input name="cfgInfo" type="text" id="cfgInfo" />
  </p>
  <p>&nbsp;</p>
  <p>
    <input type="button" name="Submit" value="GET"  onclick="doRequestUsingGET();"/>
 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 <input type="button" name="Submit2" value="POST"  onclick="doRequestUsingPost();"/>
  </p>

  <div id="serverResponse"></div>
</form>

</body>
</html>

 

总结:

其中Servlet中的 :response.setHeader("Access-Control-Allow-Origin", "*");   设置比较关键(解决跨域问题)。