我有一个用java编写的restful webservice。我用javascript调用它。
当我打电话给网络服务时,所有代码都能完美运行,但不能完美地返回值。我的代码在这里:
WS:
@RestController
public class VillageService {
@Autowired
private InnerService innerService;
@RequestMapping(value = "/services/getVillages")
public Village getAllVillages(@RequestParam int param) throws JSONException {
long startTime = System.currentTimeMillis();
Village result = innerService.getAllVillagesCacheable(param);
long stopTime = System.currentTimeMillis();
long elapsedTime = stopTime - startTime;
System.out.println("süre: " + elapsedTime);
startTime = System.currentTimeMillis();
Village result2 = innerService.getAllVillages(param);
stopTime = System.currentTimeMillis();
elapsedTime = stopTime - startTime;
System.out.println("süre cache'siz: " + elapsedTime);
return result;
}
}
JS:
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
}
});
};
当我打电话给ws时,所有" prinln"代码工作完美,但没有返回值。我的js没有完成"成功"它落入"错误:"情况下。
我该如何解决?
答案 0 :(得分:1)
您应该使用AJAX调用传递数据:
data: {param:5},
使用HTTP请求读取参数,您还需要为返回JSON的方法添加@ResponseBody
注释:
@RequestMapping(value = "/services/getVillages")
@ResponseBody
public Village getAllVillages(HttpServletRequest request) throws JSONException {
String param = request.getParameter("param");