无法将json从javascript传输到java
function check() {
var svar = document.getElementsByName("svar");
var len = svar.length;
var object = 5;
var jsonData = JSON.parse(JSON.stringify(object));
$.ajax({
type : 'POST',
url : 'http://localhost:9000/postasvar',
dataType : 'json',
contentType : 'application/json',
data : jsonData
});
}
我在javascript中获得了上述代码,目的是向java发送一个json对象
@BodyParser.Of(BodyParser.Json.class)
public static Result postaSvar(){
JsonNode json = request().body().asJson();
//String svar = json.findPath("svar").textValue();
if(json== null){
return badRequest("förväntade json");
}else{
return ok("hello " + json);
}
}
上面的java代码是用来处理来自javascript的json的代码,但我得到的答案总是空的
我的主要代码中还有以下代码。斯卡拉。html:
@(title: String)(content: Html)
<!DOCTYPE html>
<html>
<head>
<title>@title</title>
<link rel="stylesheet" media="screen" href="@routes.Assets.at("stylesheets/main.css")">
<link rel="shortcut icon" type="image/png" href="@routes.Assets.at("images/favicon.png")">
<script src="@routes.Assets.at("javascripts/check.js")" type="text/javascript"> </script>
<script src="@routes.Assets.at("javascripts/hello.js")" type="text/javascript"> </script>
</head>
<body>
@content
</body>
</html>
这是索引。斯卡拉。html:
@(message: String)
@main("Welcome to Play") {
@message
<form action="http://localhost:9000/postasvar" method="post">
</br>
<input type="radio" name="svar" value="svar1"/>svar1
<input type="radio" name="svar" value="svar2"/>svar2
<input type="radio" name="svar" value="svar3"/>svar3
<input type="radio" name="svar" value="svar4"/>svar4</br>
<button name="knappen" onclick="check();">Klar</button>
</form>
}
是不是有人知道问题出在哪里
# 1 楼答案
您需要给jQuery一个要发送的字符串,而不是一个对象。在本例中,由于jQuery没有在主体中发送任何内容,所以总是会得到null
例如,如果你这样做
jQuery将在请求正文中发送此消息
而不是JSON格式的对象(
dataType
指定它正在等待的响应类型,而不是它正在发送的数据类型)。因此,请发送一个字符串:这将发送正确的身体和预期的工作