gpt4 book ai didi

java - 无法从 javascript 获取 json 到运行中的 java

转载 作者:行者123 更新时间:2023-11-30 08:13:06 28 4
gpt4 key购买 nike

 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 中得到了上述代码,目的是将 json 对象发送到 java.util.concurrent.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的代码,但我得到的答案始终为空。

我的 main.scala.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>

这是index.scala.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>


}

是否有人知道问题所在?

最佳答案

您需要向 jQuery 提供要发送的字符串,而不是对象。在你的情况下,你总是为 null,因为 jQuery 没有在正文中发送任何内容。

例如,如果您这样做

$.ajax({
// (...)
dataType : 'json',
contentType : 'application/json',
data : {name: "Salem"}
});

jQuery 将在请求正文中发送此内容

name=Salem

而不是格式化为 JSON 的对象(dataType 指定它正在等待的响应类型,而不是它正在发送的数据类型)。因此发送一个字符串:

$.ajax({
// (...)
dataType : 'json',
contentType : 'application/json',
data : JSON.stringify({name: "Salem"})
});

这将发送正确的正文并按预期工作

{"name": "Salem"}

关于java - 无法从 javascript 获取 json 到运行中的 java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30079696/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com