随笔-84  评论-56  文章-0  trackbacks-0
 

发送请求参数

Ø 目前我们已经讲了

1、 使用Ajax技术向服务器发送请求

2、 也知道了可以采用多种方法解析服务器的响应。

Ø 只缺少一个内容,就是未将任何数据作为请求的一部分发送给服务器。

GET方法发送请求参数

Ø GET方法:作为名/值对放在请求URL 中传递。

      * 资源URL 的问号后面就是名/值对。

      * 名/值对用 name=value 的形式,

       *  用与号(&)分隔。

Ø 例如:

http://localhost:8080/projectName?name=yifeng&password=hello

POST 方法发送请求参数

Ø POST 方法:将参数串放在请求体中发送。

* 参数编码为名/值对,形式为name=value

* 用与号(&)分隔。

使用GETPOST的建议

Ø 获取数据时应当使用GET 方法。

    * 数据处理不改变数据模型的状态。

Ø 存储、更新数据,使用POST 方法。

    * 操作改变了数据模型的状态。

Ø 特点。

* GET 请求的参数编码到请求URL 中,可以为该URL 建立书签。(不过,如果是异步请求就没有什么用。)

* GET 请求发送的数据量通常是固定的,而POST 方法可以发送任意量的数据。

DEMO AJAX以名/值对发送请求参数

Ø 使用GET请求和POST请求,创建查询字符串技术是一样的。

Ø 唯一的区别是,GET发送请求时,查询字符串追加到请求URL中,

Ø POST方法时,在XHR对象的send()方法时发送查询串。

Ø DEMO

getAndPostExample.html文件

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

        "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

    <title>Dynamically Editing Page Content</title>

    <script type="text/javascript" language="javascript">

        var xmlHttp;

        function createXMLHttpRequest() {

            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() {

            createXMLHttpRequest();

            var queryString = "GetAndPostExample?";

            queryString = queryString + createQueryString() + "&timeStamp=" + new Date().getTime();

            xmlHttp.onreadystatechange = handleStateChange;

            xmlHttp.open("GET", queryString, true);

            xmlHttp.send(null);

        }

        function doRequestUsingPOST() {

            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>Entery your first name, middle name, and birthday:</h1>

<table>

    <tbody>

        <tr>

            <td>First name:</td>

            <td><input type="text" id="firstName"/></td>

        </tr>

        <tr>

            <td>Middle name:</td>

            <td><input type="text" id="middleName"></td>

        </tr>

        <tr>

            <td>Birthday:</td>

            <td><input type="text" id="birthday"/></td>

        </tr>

    </tbody>

</table>

<form action="#">

    <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>

GetAndPostExample.java文件

package org.yifeng.webapp.servlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.ServletException;

import java.io.IOException;

import java.io.PrintWriter;

/**

 * Copyright:       晟软科技

 * WebSit:          http://www.shengruan.com

 * Author:          忆风

 * QQ:              583305005

 * MSN:             YiFengs@msn.com

 * Email:           zhdqCN@gmail.com

 * CreationTime:    2008-8-25 22:44:44

 * Description:

 */

public class GetAndPostExample extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/xml");

        String firstName = request.getParameter("firstName");

        String middleName = request.getParameter("middleName");

        String birthday = request.getParameter("birthday");

        StringBuilder responseText = new StringBuilder();

        responseText.append("Hello, ").append(firstName).append(" " + middleName)

                .append(". Your birthday is " + birthday + ".")

                .append("[Method: " + request.getMethod() + "]");

        PrintWriter out = response.getWriter();

        out.println(responseText);

        out.flush();

        out.close();

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        doPost(request, response);

    }

}

Web.xml配置

<?xml version="1.0" encoding="UTF-8"?>

<web-app 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"

           version="2.5">

    <servlet>

        <servlet-name>GetAndPostExample</servlet-name>

        <servlet-class>org.yifeng.webapp.servlet.GetAndPostExample</servlet-class>

    </servlet>

    <servlet-mapping>

        <servlet-name>GetAndPostExample</servlet-name>

        <url-pattern>/GetAndPostExample</url-pattern>

    </servlet-mapping>

    <welcome-file-list>

        <welcome-file>getAndPostExample.html</welcome-file>

    </welcome-file-list>

</web-app>

如果以点击“Send parameters using GET”按钮,如下图:

如果以点击“Send parameters using POST”按钮,如下图:

也许你会疑问,为什么要在URL后面追加时间呢?

有时浏览器会把多个XMLHttpRequest 请求的结果缓存在同一个URL.

如果对每个请求的响应不同,这就会带来不好的结果.

把当前时间戳追加到 URL的最后,就能确保URL 的唯一性,从而避免浏览器缓存结果.

* IE有这种缓存问题,但是Firefox没有。你可以去试试,哈哈。

AJAX XML 发送请求数据

Ø 只是使用一个包含名/值对的简单查询串,这可能不够健壮,

Ø 不足以向服务器传递大量复杂的模型变化.

Ø 可以应用XML

Ø 如何向服务器发送XML ?

Ø 可以把XML 作为请求体的一部分发送到服务器,

Ø 这与POST 请求中将查询串作为请求体的一部分进行发送异曲同工.

Ø 服务器可以从请求体读到XM L,并加以处理。

Ø DEMO

Ø postingXML.html

DEMO AJAX XML 发送请求数据

Ø 撰写“postingXML.html”文件,如下:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

        "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

    <title>Sending and XML Request</title>

    <script type="text/javascript">

        var xmlHttp;

        function createXMLHttpRequest() {

            if (window.ActiveXObject) {

                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");

            } else if (window.XMLHttpRequest) {

                xmlHttp = new XMLHttpRequest();

            }

        }

        /**

         * 生成XML

         */

        function createXML() {

            var xml = "<pets>";

            var options = document.getElementById("petTypes").childNodes;

            var option = null;

            for (var i = 0; i < options.length; i++) {

                option = options[i];

                if (option.selected) {

                    xml = xml + "<type>" + option.value + "<"/type>";

                }

            }

            xml = xml + "<"/pets>";

            return xml;

        }

        function sendPetTypes() {

            createXMLHttpRequest();

            var xml = createXML();

            var url = "PostingXMLExample?timeStamp=" + new Date().getTime();

            xmlHttp.open("POST", url, true);

            xmlHttp.onreadystatechange = handleStateChange;

            xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

            xmlHttp.send(xml);

        }

        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>Select the types of pets in your home:</h1>

<form action="#">

    <select id="petTypes" size="6" multiple="true">

        <option value="cats">Cats</option>

        <option value="dogs">Dogs</option>

        <option value="fish">Fish</option>

        <option value="birds">Birds</option>

        <option value="hamsters">Hamsters</option>

        <option value="rabbits">Rabbits</option>

    </select>

    <br/><br/>

    <input type="button" value="Submit Pets" onclick="sendPetTypes();"/>

</form>

<h2>Server Response:</h2>

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

</body>

</html>

Ø 撰写“PostingXMLExample.java”文件,如下:

package org.yifeng.webapp.servlet;

import org.w3c.dom.Document;

import org.w3c.dom.NodeList;

import org.xml.sax.SAXException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.ServletException;

import javax.xml.parsers.DocumentBuilderFactory;

import javax.xml.parsers.ParserConfigurationException;

import java.io.IOException;

import java.io.BufferedReader;

import java.io.ByteArrayInputStream;

/**

 * Copyright:       晟软科技

 * WebSit:         http://www.shengruan.com

 * Author:          忆风

 * QQ:              583305005

 * MSN:             YiFengs@msn.com

 * Email:           zhdqCN@gmail.com

 * CreationTime:    2008-8-25 23:30:41

 * Description:

 */

public class PostingXMLExample extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String xml = readXMLFromRequestBody(request);//获得XML字符串

        Document xmlDoc = null;

        try {

            xmlDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(xml.getBytes()));

        } catch (SAXException e) {

            System.out.println("SAXException: " + e);

        } catch (ParserConfigurationException e) {

            System.out.println("ParserConfigurationException: " + e);

        }

        /**

         * JavaJavaScript均有W3C DOM的实现,比如getElementByTagNamegetNodeValue方法

         */

        NodeList selectedPetTypes = xmlDoc.getElementsByTagName("type");

        String type = null;

        String responseText = "Selected Pets: ";

        for (int i = 0; i < selectedPetTypes.getLength(); i++) {

            type = selectedPetTypes.item(i).getFirstChild().getNodeValue();

            responseText = responseText + " " + type;

        }

        response.setContentType("text/xml");

        response.getWriter().print(responseText);

    }

    private String readXMLFromRequestBody(HttpServletRequest request) {

        StringBuilder xml = new StringBuilder();

        String line = null;

        try {

            BufferedReader reader = request.getReader();

            while ((line = reader.readLine()) != null) {

                xml.append(line);

            }

        } catch (Exception e) {

            System.out.println("Error reading XML: " + e.toString());

        }

        return xml.toString();

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        doPost(request, response);

    }

}

Ø 运行,显示如下:





作者:周大庆(zhoudaqing)
网址:http://www.blogjava.net/yifeng
>>>转载请注明出处!<<<

posted on 2008-08-26 02:47 忆风 阅读(214) 评论(0)  编辑  收藏 所属分类: Ajax

只有注册用户登录后才能发表评论。


网站导航: