LoginSignup
3
3

More than 5 years have passed since last update.

SpringMVC Ajaxでプルダウン表示データ取得&Ajax受信データの文字化け対応

Posted at

あるプルダウンを選択したら別のプルダウンリストの表示候補を切り替えるやり方について下記2パターンのうちどっちでやろうか悩んでました。

1.全パターンをあらかじめ画面に設定してプルダウン変更時に画面上で切り替える
2.プルダウン変更時にAjaxでデータを取得する

1.の方法は切り替え処理が面倒だったので2.の方法でやることにしました。

home.html
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring4-4.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Insert title here</title>
</head>
<body>

<div>
    <select id="select1" style="width: 80px;">
        <option value="nothing">-</option>
        <option value="001">北海道</option>
        <option value="002">東北</option>
        <option value="003">北陸</option>
        <option value="004">関東</option>
    </select>
    <select id="select2" style="width: 80px;">
        <option value="nothing">-</option>
    </select>
</div>

<script th:src="@{/resources/js/jquery-1.12.4.min.js}" src="../../../resources/js/jquery-1.12.4.min.js"></script>
<script>
$(function () {
    $("#select1").change(function() {
        $.ajax({
            type: "POST",
            url: "select",
            data: "select1=" + $("#select1").val(),
            dataType: "text",
            success: function(msg) {
                $("#select2").html(msg);
            }
        });
    });
});
</script>
</body>
</html>

jqueryでid="select1"のプルダウン切り替え時にAjax通信するように設定
データ取得できたらid="select2"のプルダウンのhtmlを書き換える

HomeController.java
package jp.co.test.controller;

import java.util.List;
import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import jp.co.test.service.HomeService;

@Controller
public class HomeController {

    private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

    @Autowired
    private HomeService homeService;

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String home(Locale locale, Model model) {
        return "home";
    }

    @RequestMapping(value = "/select", method = RequestMethod.POST)
    @ResponseBody
    public String getSelectData(String selectValue) {
        logger.info("start");

        StringBuilder sb = new StringBuilder("<option value=\"nothing\">-</option>");

        List<String> selectDataList = homeService.getSelectData(selectValue);
        selectDataList.stream()
            .map(value -> String.format("<option value=\"%s\">%s</option>", value, value))
            .forEach(option -> sb.append(option));

        logger.info(sb.toString());

        logger.info("end");
        return sb.toString();
    }

}

Controller側の処理ではタグ付きのデータを返すように設定
んで動作させてみるとあれ?文字化けしている。。

image

Ajaxで受信したデータが文字化けしてました。
色々調べてみるとControllerのRequestMappingに「produces = "text/plain;charset=UTF8"」を追加すると解決するようです。

image

無事解決しましたが、文字化けに関してはいろいろあって大変ですね~

参考リンク

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3