我有一个用java编写的宁静的Web服务。我从javascript调用它。我传递一个字符串参数(param = 5)。但是我需要发送一个对象来传递它。 如何从javascript端传递restful webservice中的对象?我如何在java方面解析它?
java代码:
@RequestMapping(value = "/services/getVillages")
@ResponseBody
public Village getAllVillages(HttpServletRequest request) throws JSONException {
String param = request.getParameter("param");
System.out.println("parametre: " + param );
long startTime = System.currentTimeMillis();
//Village result = innerService.getAllVillagesCacheable(request);
long stopTime = System.currentTimeMillis();
long elapsedTime = stopTime - startTime;
System.out.println("süre: " + elapsedTime);
startTime = System.currentTimeMillis();
//Village result2 = innerService.getAllVillages(new HttpServletRequest());
stopTime = System.currentTimeMillis();
elapsedTime = stopTime - startTime;
System.out.println("süre cache'siz: " + elapsedTime);
return new Village(); }
javascript代码:
function callWS()
{
$.ajax({
type: 'GET',
url: 'http://localhost/services/getVillages/',
data: "param=5", // the data in form-encoded format, ie as it would appear on a querystring
dataType: "json", // the data type we want back, so text. The data will come wrapped in xml
success: function (data) {
alert("party hard"); // show the string that was returned, this will be the data inside the xml wrapper
},
error: function (data) {
alert("restful cagirmada hata"); // show the string that was returned, this will be the data inside the xml wrapper
}
});
};
答案 0 :(得分:1)
虽然您可以通过将对象放入请求的data属性来传递带有get事件的对象,但我建议使用post方法。 post方法允许将对象放入请求的主体中,这在处理复杂对象时更容易通过。
$.ajax({
type: 'POST',
url: 'http://localhost/services/getVillages/',
data: {val1: 1, val2: 2, val3: 3},
dataType: "json",
success: function (data) {
alert("party hard");
},
error: function (data) {
alert("restful cagirmada hata");
}
});
如上所示执行此操作将创建一个post请求并将该对象添加到该请求的正文中。
使用简单对象,您可以使用get来执行此操作,并将属性放入查询字符串中,但我建议使用帖子并将对象放入正文中。