我想做的是通过用户交互从我的前端代码发起 ajax 调用。这调用了我编写的 Java Restful 服务。这个Java函数调用另一个服务。
我需要中间的java服务,因为我需要以“MyModel”的格式将输入发送到其他服务。
问题是,AJAX 调用可以工作,但无法获取我发送的 JSON 对象。您可以在下面的 Java 函数中看到,我第二次创建了“param1”:“asdasd”。这是因为它无法从前端获取JSON数据。它应该使用 sendInputs 函数的参数动态创建。
顺便说一句,当我调试时,值字符串输入是这样的:“”
Javascript AJAX 调用:
var paramData = {"param1" : "asdasd"};
$.ajax({
type : 'GET',
url : "/api/v2/proxy",
dataType : "json",
headers : {
"Service-End-Point" : "http://localhost:9000/service/myService/sendInputs"
},
statusCode : {
200 : function(data) {
}
},
contentType : "application/json",
data : JSON.stringify(paramData),
error : function(error) {
}
});
Java 消耗:
@GET
@Path("/sendInputs")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public String sendInputs(String input) {
String result = null;
//define the service endpoint to be added the default URL
String serviceEndpoint = "otherService/tool/runTool";
List<MyModel> modelParameterList = new ArrayList<MyModel>();
MyModel inputParameter = null;
inputParameter = new MyModel("param1", "asdasd");
modelParameterList.add(inputParameter);
//convert the Java Map to a json string using Jackson ObjectMapper
String jsonStringOfInputParameters = toJSON(modelParameterList);
WebClient client = WebClient
.create("http://localhost:9000");
result = client.path(serviceEndpoint)
.query("tool", "myTool")
.query("input", jsonStringOfInputParameters)
.accept("application/json")
//tells cxf to convert the json to a string type upon return
.get(String.class);
// Return the json result as a string
return result;
}
最佳答案
您的 paramData
变量已经是有效的 json。我认为您不需要再次使用 JSON.Stringify()
。这是什么 ajax 调用:
statusCode : {
200 : function(data) {
}
}
状态代码应该来自服务器作为响应。
关于java - 如何将 JSON 对象从 Javascript 传递到 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30409936/