我正在尝试使用Jquery-Ajax使用JSON响应,但是它不起作用。空选择下拉列表正在加载

Below is the SOAPUI (GET) response when I hit: http://localhost:8082/getCountries

HTTP / 1.1 200

Content-Type =应用程序/ json

Transfer-Encoding =分块

日期= 2020年5月18日星期一03:38:46 GMT

保持活动=超时= 60

连接=保持活动

[{“ countryId”:91,“ countryName”:“印度”},{“ countryId”:94,“ countryName”:“斯里兰卡”}]

下面是带有Jquery-Ajax代码的jsp页面:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Cascading Dropdown</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
    alert("Hello");
    $.ajax({
        url: "http://localhost:8082/getCountries"
    }).then(function(result) {
        alert("Success");
        var result = JSON.parse(result);
        var s = '';
        for(var i = 0; i < result.length; i++) {
            s += '<option value="' + result[i].countryId + '">' + result[i].countryName + '</option>';
        }
        $('#comboboxCountry').html(s);
    });
});



</script>

</head>
<body>

    <form>

        <table>
            <tr>
                <td>Country</td>
                <td>

<select id="comboboxCountry" style="width: 200px"></select>

                </td>

            </tr>

        </table>

    </form>

</body>
</html>

我在这里使用两个项目。一个正在生成JSON数组,另一个正在使用。我在下面发布了两个控制器:

  1. Producing Controller:

    @Controller
    public class MainController {
    
    
        @Autowired
        private MainService mainService;
    
        @ResponseBody
        @GetMapping(path = "/getCountries",produces = "application/json")
        public List<Country> getCountires(){
    
            return mainService.findAll();
        }
    
        @ResponseBody
        @GetMapping(path = "/getStates/{countryId}",produces = "application/json")
        public List<State> getStates(@PathVariable("countryId") Integer countryId){
            return mainService.findbyId(countryId);
        }
    
    }
    
  2. Consuming controller:

    @Controller
    public class MainController {
    
    
        @RequestMapping("/")
        public String home(Model model) {
            System.out.println("loading welcome page");
    
    
            return "welcome";
        }
    }
    
评论