liguofeng29’s blog

個人勉強用ブログだっす。

Ajax - レスポンス処理

XMLHttpRequestがレスポンスを処理するための属性は

  1. responseText
  2. responseXML

JSONレスポンスを処理するサンプル

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>XMLリクエスト送信</title>
<style type="text/css">
select {
    width: 120px;
    font-size: 11pt;
}
</style>
</head>
<body>
    <!-- 支持多选的列表框 -->
    <label>国コード</label>
    <select name="country" id="country" size="5">
        <option value="392" selected="selected">392</option>
        <option value="156">156</option>
        <option value="620">620</option>
    </select>
    <br>
    <!-- Ajax送信 -->
    <input type="button" value="国情報取得" onClick="send();" />
    <br>
    <label>国名 : </label>
    <label id="name"></label>
    <br>
    <label>位置 : </label>
    <label id="location"></label>
    <script type="text/javascript">
       // XMLHttpRequest
       var xmlrequest;
       function createXMLHttpRequest() {
           if (window.XMLHttpRequest) {
               // DOM2
               xmlrequest = new XMLHttpRequest();
           }
           // IE
           else if (window.ActiveXObject) {
               try {
                   xmlrequest = new ActiveXObject("Msxml2.XMLHTTP");
               } catch (e) {
                   try {
                       xmlrequest = new ActiveXObject("Microsoft.XMLHTTP");
                   } catch (e) {
                   }
               }
           }
       }
       // 送信
       function send() {
           // XMLHttpRequest初期化
           createXMLHttpRequest();
           // URL
           var uri = "/ajax/getCountryInfo?aaa=111";
           // 接続
           xmlrequest.open("POST", uri, true);
           // ヘッダ
           xmlrequest.setRequestHeader("Content-Type",
                   "application/x-www-form-urlencoded");
           // 状態変更関数
           xmlrequest.onreadystatechange = processResponse;
           var countryCode = document.getElementById("country").value;
           // XMLデータ送信
           xmlrequest.send("code=" + countryCode);
       }
       // レスポンス処理
       function processResponse() {
           if (xmlrequest.readyState == 4) {
               if (xmlrequest.status == 200) {
                   var country = JSON.parse(xmlrequest.responseText)
                   document.getElementById("name").innerText = country.name;
                   document.getElementById("location").innerText = country.location;
               }
           }
       }
   </script>
</body>
</html>
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.arnx.jsonic.JSON;

@WebServlet(urlPatterns = "/getCountryInfo")
public class GetCountryInfoServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    private List<Country> countryList = new ArrayList<Country>();
    {
        Country japan = new Country();
        japan.code = "392";
        japan.name = "Japan";
        japan.location = "東アジア";

        Country china = new Country();
        china.code = "156";
        china.name = "China";
        china.location = "東アジア";

        Country portugal = new Country();
        portugal.code = "620";
        portugal.name = "Portugal";
        portugal.location = "西ヨーロッパ";

        countryList.add(japan);
        countryList.add(china);
        countryList.add(portugal);
    }

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

        String code = (String) request.getParameter("code");
        Country ret = null;

        try {
            for (Country c : countryList) {

                // 国情報あり
                if (c.code.equals(code)) {
                    ret = c;
                    break;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        // 出力
        PrintStream out = new PrintStream(response.getOutputStream());
        out.println(JSON.encode(ret));
    }
}

class Country {
    public String code;
    public String name;
    public String location;
}

f:id:liguofeng29:20160221145330g:plain