java - 从 javascript 调用 java Restful Webservice 时返回值失败

标签 java javascript web-services rest

我有一个用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/

相关文章:

javascript - 我需要在 ajax 响应后重新创建多选

javascript - Loopback/SQL中如何查询相关模型的个数?

java - 对 Jersey 休息服务的并发请求

java - 无法通过在 Grails 中使用 REST Web 服务来下载 pdf 文件

php - ReSTLer 总是返回未找到

java - 在基本 Java 程序中返回错误值

java - 通过连接前 n 个自然数的二进制表示形式形成的数字的十进制值

java - 使用 BufferedReader 和 Scanner 读取文本文件

java - 输入标签无法正常使用 JQuery Ajax

javascript - 当需要类似 sleep 的功能时如何重构 javascript 代码?