首页 > 解决方案 > 我正在尝试使用 Jquery-Ajax 使用 JSON 响应,但它不起作用。正在加载空选择下拉列表

问题描述

以下是我点击时的 SOAPUI (GET) 响应: http://localhost:8082/getCountries

HTTP/1.1 200

内容类型=应用程序/json

传输编码=分块

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

保活=超时=60

连接=保持活动状态

[{"countryId":91,"countryName":"India"},{"countryId":94,"countryName":"SriLanka"}]

下面是带有 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. 生产控制器:

    @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. 消费控制器:

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

标签: jqueryjsonajaxapiweb-services

解决方案


现在我知道这是一个愚蠢的问题。但是这个答案可能会帮助新手并尝试学习。

这个问题可以通过注释你的控制器来解决,比如:

 @CrossOrigin(origins = "requesting host url goes here", maxAge = 3600)

推荐阅读