Spring Boot 控制器方法:
@PostMapping("/bills/add")
@ResponseBody
public String createBill(@RequestParam String currency) {
String phone = authentication().getName();
String answer = null;
if(currency.isEmpty()) {
answer = "Please choose currency type";
return answer;
}
accountService.addBill(phone, currency);
answer = "Success!!!";
return answer;
}
百里香叶:
<div>
<form id="currency_form">
<select class="form-control" th:id="currency" th:name="currency" style="width:auto">
<option value="">Select currency</option>
<option th:each="currency : ${T(com.github.irybov.bankdemoboot.Currency).values()}"
th:value="${currency.name()}"
th:text="${currency.name()}">
</option>
</select>
<button type="submit" class="btn btn-success add_bill">
Add new bill</button>
<p th:text="${message}" th:value="${#strings.isEmpty('currency')}" class="error"/>
</form>
</div>
jQuery:
<script>
$(document).ready(function(){
$('.add_bill').click(function(){
var type = ('#currency').val();
$('#currency_form').submit(function (ev) {
ev.preventDefault();
$.ajax({
type: 'POST',
url: 'http://localhost:8080/bankdemo/bills/add?currency='+type,
success: function(msg) {
alert(msg);
}
error: function (xhr, statusText, err) {
alert(xhr.status);
}
});
});
});
});
</script>
HTML 最初生成于
http://localhost:8080/bankdemo/accounts/show
@GetMapping("/accounts/show")
public String getAccount(ModelMap modelMap) {
String current = authentication().getName();
AccountResponseDTO account = accountService.getAccountDTO(current);
modelMap.addAttribute("account", account);
modelMap.addAttribute("currencies", currencies);
return "/account/private";
}
所以问题是由于某种原因,在做 AJAX 时,url 变成了浏览器行
http://localhost:8080/bankdemo/accounts/show?currency=USD
而不是沿着脚本中指定的路径执行请求。
如果您通过 Postman 手动输入正确的 url,则控制器方法工作正常,返回响应字符串和状态 200。
我相信一切都是因为您试图通过地址栏传输数据。
这是一个 POST 请求,这意味着数据必须通过请求体传递。
为此有一个数据参数。
尝试以下
转发 CSRF