首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > Ajax >

ajax利用servlet发送请求,不要form中的action=.

2012-12-25 
ajax利用servlet发送请求,不用form中的action...如果数据处理不改变数据模型的状态,理论上采用GET方法,获

ajax利用servlet发送请求,不用form中的action=...
如果数据处理不改变数据模型的状态,理论上采用GET方法,获取数据时应用GET方法。如果因为存储、更新数据,或者发送电子邮件,操作改变了数据模型的状态,应该使用POST方法。

  使用httpxmlrequest请求的话,将使用javascript创建查询串,来提交请求。使用GET发送请求send(null)。POST:send(...)。而不再用form的GET/POST,这样浏览器的url部分也不会出现。。?.....&....&...一连串的东西了。。。。

  例子:getAndPostExample.html:

<html>
<head>
<title>Sending Request Data Using GET and POST</title>

<script type="text/javascript">
   var xmlHttp;

function createXMLHttpRequest() {//创建xmlhttprequest对象。
    if (window.ActiveXObject) {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if (window.XMLHttpRequest) {
        xmlHttp = new XMLHttpRequest();
    }
}
   
function createQueryString() {//创建查询串
    var firstName = document.getElementById("firstName").value;
    var middleName = document.getElementById("middleName").value;
    var birthday = document.getElementById("birthday").value;   
    var queryString = "firstName=" + firstName + "&middleName=" + middleName
        + "&birthday=" + birthday;
     return queryString;
}

function doRequestUsingGET() {//Get的主js
    createXMLHttpRequest();   
    var queryString = "GetAndPostExample?";
    queryString = queryString + createQueryString()
        + "&timeStamp=" + new Date().getTime();
    xmlHttp.onreadystatechange = handleStateChange;
    xmlHttp.open("GET", queryString, true);
   xmlHttp.send(null);
}

function doRequestUsingPOST() {//POST的主js
    createXMLHttpRequest();   
    var url = "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 handleStateChange() {
    if(xmlHttp.readyState == 4) {
        if(xmlHttp.status == 200) {
            parseResults();
        }
    }
}

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

</script>
</head>

<body>
<h1>Enter your first name, middle name, and birthday:</h1>

<table>
    <tbody>
        <tr>
            <td>First name:</td>
            <td><input type="text" id="firstName"/>
        </tr>
        <tr>
            <td>Middle name:</td>
            <td><input type="text" id="middleName"/>
        </tr>
        <tr>
            <td>Birthday:</td>
            <td><input type="text" id="birthday"/>
        </tr>
    </tbody>

</table>

<form action="#">//这个时候向服务器发送请求就不用form action出马了,ajax自己能做了。
    <input type="button" value="Send parameters using GET" onclick="doRequestUsingGET();"/>       
    <br/><br/>
    <input type="button" value="Send parameters using POST" onclick="doRequestUsingPOST();"/>   
</form> <br/>
<h2>Server Response:</h2>

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

</body>
</html>

处理请求的servlet:

package three;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class GetAndPostExample extends HttpServlet {
   
   protected void processRequest(HttpServletRequest request,
            HttpServletResponse response, String method)
    throws ServletException, IOException {//自定义的一个方法,因为get与post都要用到。参数跟doPost\doGet差不多,抛出的异常也差不多
       
        //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 browser
        PrintWriter out = response.getWriter();
        out.println(responseText);

        //Close the writer
        out.close();
    }
   
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        //Process the request in method processRequest
        processRequest(request, response, "GET");
    }
   
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        //Process the request in method processRequest
        processRequest(request, response, "POST");
    }
}

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"   xmlns="http://java.sun.com/xml/ns/javaee"   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee  http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <servlet>
<servlet-name>GetAndPostExample</servlet-name>
<servlet-class>three.GetAndPostExample</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>GetAndPostExample</servlet-name>
    <url-pattern>/three/GetAndPostExample</url-pattern>//注意,包名three要包含进去,因为你访问页面地址是:http://localhost:8080/ajaxfoundation/three/getAndPostExample.html,
 
</servlet-mapping>
</web-app>

运行结果是:(注意浏览器上方没有一连串的提交数据)







http://hi.baidu.com/sun1227/blog/item/41b46a4eb3cd1531aec3ab7c.html

热点排行