我有一个用java编写的restful webservice。我用 JavaScript 调用它。
当我调用 Webservice 时,所有代码都可以完美运行,但不能完美返回值。我的代码在这里:
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 没有以“成功”结束,它陷入“错误:”情况。
如何修复它?
最佳答案
您应该使用 AJAX 调用传递数据,如下所示:
data: {param:5},
使用 HTTP Request 读取参数,返回 JSON 的方法还需要有 @ResponseBody
注解:
@RequestMapping(value = "/services/getVillages")
@ResponseBody
public Village getAllVillages(HttpServletRequest request) throws JSONException {
String param = request.getParameter("param");
关于java - 从 javascript 调用 java Restful Webservice 时返回值失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24484160/