jquery - 我正在尝试使用 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 数组,另一个正在消耗。我在下面发布了两个控制器:
生产控制器:
@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); } }
消费控制器:
@Controller public class MainController { @RequestMapping("/") public String home(Model model) { System.out.println("loading welcome page"); return "welcome"; } }
解决方案
现在我知道这是一个愚蠢的问题。但是这个答案可能会帮助新手并尝试学习。
这个问题可以通过注释你的控制器来解决,比如:
@CrossOrigin(origins = "requesting host url goes here", maxAge = 3600)
推荐阅读
- php - Laravel Eloquent:我的数据透视表有关系
- django - 如何在 django 模型字段上存储多个值
- reactjs - 如何在 React 项目中显示图像预览?
- powerbi - 在 Power BI 中创建一个 True/False 输出列,用于评估包含文本字符串的列
- json - Flutter:如何将字符串转换为地图
在json中 - collections - Mapstruct:将集合映射到对象
- c# - 为什么 staticpropertychanged 为空?
- sql - 基于 2 列 PostgreSQL 创建序列
- function - 在 Kotlin 中显示不同行为的块体和表达式体函数
- android - 以编程方式在 Android 中的 ImageView 内的 VectorDrawable 上应用渐变