免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2531 | 回复: 0
打印 上一主题 下一主题

Ajax与服务器通信:发送请求和处理响应 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-12-23 03:47 |只看该作者 |倒序浏览
[ 本帖最后由 tkchks 于 2011-12-25 19:14 编辑 ]

要想充分发挥ajax的强大功能,这要求你向服务器发送一些上下文数据。

XMLHttpRequest对象的工作与以往惯用的HTTP技术(GET和POST)是一样的。

在下面的例子中,主要介绍这两种请求方式。
其中GET请求,我们想应用程序发送了3个参数:firstName,middleName,birthday.
其中资源URL和参数之间要用一个问号(?),问号后面就是名/值对。其采用name=value的形式,各个名值对之间用与(&)号分隔。
如:http://localhost:8080/yourapp/servlet/GetAndPostExample?firstName=Harry&middleName=Poter&birthday=20101010

服务器知道如何获取URL中的命名参数。

采用POST方法向服务器发送命名参数时,与采用GET时类似。POST方法也会将参数编码为名/值对。
这两种方式的主要区别在于,POST方法将参数串放在请求体中发送,而GET方法是将参数追加到URL中发送。

该示例有两个文件,其一为getandpost.html,另一个为servlet GetAndPostExample.java

详细代码如下:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <title>getAndPost.html</title>
        <meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script language="javascript" type="text/javascript">
  var xmlHttp;
  function createXMLHttpRequest(){
    if(window.ActiveXObject)
      {
         xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
      }
      else if(window.XMLHttpRequest)
      {
        xmlHttp = new XMLHttpRequest();
      }else{
        alert("浏览器不支持XMLHttpRequest对象");
      }
  }
  
  function createQueryString(){
    var firstName = document.getElementById("firstName").value;//document.getElementById("firstName").value;
    //alter(document.getElementById("firstName").value);
    var middleName = document.getElementById("middleName").value;
    var birthday = document.getElementById("birthday").value;
  //var birthday = document.getElementByID("birthday").value; //这句是错的!!!因为ID的d要小写!!!!!
   
    var queryString = "firstName="+ firstName + "&middleName="+ middleName + "&birthday=" + birthday;
    //alert(queryString);
    return queryString;
  }
  
  function doRequestUsingPOST(){
    createXMLHttpRequest();
   
    var url = "servlet/GetAndPostExample?timeStamp=" + new Date().getTime();
    var queryString = createQueryString();
    xmlHttp.open("POST",url,true);
   
    xmlHttp.onreadystatechange = handleStateChange;
   
    xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");
    xmlHttp.send(queryString);
  }
   function doRequestUsingGET(){
   
     createXMLHttpRequest();

     
       var queryString = "servlet/GetAndPostExample?";
     //alert(createQueryString());
     queryString = queryString + createQueryString() + "&timeStamp=" + new Date().getTime();
     alert("oo");
     xmlHttp.onreadystatechange = handleStateChange;
     xmlHttp.open("GET",queryString,true);
   
     xmlHttp.send(null);
  }
  function handleStateChange(){
     if(xmlHttp.readyState == 4){
        if(xmlHttp.status == 200){
           parseResult();
           alert("OK");
        }
     }
  }
  
  function parseResult(){
    var responseDiv = document.getElementById("serverResponse");
    if(responseDiv.hasChildNodes()){
      responseDiv.removeChild(responseDiv.childNodes[0]);
    }
    var responseText = document.createTextNode(xmlHttp.responseText);
    responseDiv.appendChild(responseText);
  }
  
  function test(){
  
    alert(document.getElementById("firstName").value);
  }
  </script>
    </head>

    <body>
        <h2>
            Enter your first name, middle name ,and birthday:
        </h2>
        
        <form action="#" id="form1" name="form1" >
         <table>
            <tbody>
                <tr>
                    <td>
                        First Name:
                    </td>
                    <td>
                        <input type="text" id="firstName" value="Harry" />
                    </td>
                </tr>
                <tr>
                    <td>
                        Middle Name:
                    </td>
                    <td>
                        <input type="text" id="middleName" value="Poter" />
                    </td>
                </tr>
                <tr>
                    <td>
                        Birthday:
                    </td>
                    <td>
                        <input type="text" id="birthday" value="2020-8-9" />
                    </td>
                </tr>
            </tbody>

        </table>
            <input type="button" value="Send parameters using GET"
                onclick="doRequestUsingGET();" />
            <input type="button" value="Send parameters using POST"
                onclick="doRequestUsingPOST()" />
         <input type="button" value="Test"
                onclick="return test()" />

        </form>
        <br />
        <h2>
            Server Response:
        </h2>
        <div id="serverResponse">
            这里将会显示来自服务器端的相应信息
        </div>
    </body>
</html>


package ajax.study;

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;

public class GetAndPostExample extends HttpServlet {

   
    protected void processRequest(HttpServletRequest request,HttpServletResponse response,String method)
    throws ServletException, IOException{
        //set content type of the response to text/xml
        response.setContentType("text/xml");
        
        //get the user's input
        String firstName = request.getParameter("firstName");
        String middleName = request.getParameter("middleName");
        String birthday = request.getParameter("birthday");
        
        //Create the response text
        String responseText = "hello "+ firstName + " " + middleName +". Your birthday is " + birthday +"."
        + "[Method: " + method + "]";
        
        //write the response back to the brower
        PrintWriter out = response.getWriter();
        out.println(responseText);
        
        //close the writer
        out.close();
        
        
    }
   


   
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //process the request in method processRequest
        processRequest(request,response,"GET");
        
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //process the request in method processRequest
        processRequest(request,response,"POST");
    }

   

}
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP