【问题标题】:How to return json object from servlet using angularjs如何使用angularjs从servlet返回json对象
【发布时间】:2018-01-30 14:35:07
【问题描述】:

我想在 angularjs 中从 servlet 返回我的 json 对象,我编写了一个 Angular 应用程序,它没有给出任何错误,但也没有获取数据。我无法正确搜索,因为我的英语有些不足,请有人帮助我 这是我的代码

Angularjs

<div ng-app="myApp" ng-controller="customersCtrl"> 

<ul>
    <li ng-repeat="x in myData">
        {{ x.1}}
    </li>
</ul>

<script>
  var app = angular.module('myApp', []);
app.controller('customersCtrl', function ($scope, $http) {
    $http.get("first").then(function (res) {
        $scope.myData = res.data.jso;
    });
});</script>>

这里是我的 doGet 方法,我的 json 对象在里面;

    @Override
public void doGet(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {
    try {
        res.setContentType("text/html");
        PrintWriter pw = res.getWriter();

        Connection conn = DriverManager.getConnection(url, uname, pass);
        Statement stmt = conn.createStatement();

        ResultSet rs = stmt.executeQuery(query);    

        while (rs.next()) {


            JSONObject jso = new JSONObject();

            jso.put("1", rs.getString(1));
            jso.put("2", rs.getString(2));
            jso.put("3", rs.getString(3));
            jso.put("4", rs.getString(4));
            jso.put("6", rs.getString(6));
            jso.put("8", rs.getString(8));
            pw.print(jso);         
        }
        conn.close();
        rs.close();
        pw.close();
        stmt.close();
        pw.flush();

    } catch (Exception e) {
        out.println(e.getMessage());
    }

}

【问题讨论】:

  • 您尝试使用 x["1"] 的出租车吗?
  • 使用console.log($scope.myData); 看看会打印什么
  • 我都试过了,但没有成功没有错误没有数据

标签: java angularjs json servlets


【解决方案1】:

我写了一个角度应用程序,它没有给出任何错误,但也没有获取数据。

在您的通话中,您没有实现错误回调,因此:

$http.get("first").then(function (res) {
    $scope.myData = res.data.jso;
});

改为:

$http.get("first").then(function (res) {
    console.log(res);
    $scope.myData = res.data.jso;
}, function (error) {
   console.error(error);
});

它将为您提供有关问题的更多信息

【讨论】:

  • 它工作 chrome 没有显示错误。我用 mozilla 打开我在控制台中获取了我的数据,但我在页面上看不到。我在哪里弄错了?
  • @TPBAFK 你能发布日志吗?
  • pastebin.com/6vEgdFyd 我偶然 (x.1) 到 (x.res) 并且同样的问题没有错误,html 中没有数据。就在控制台,控制台没有错误
  • @TPBAFK 您的数据在data 键下。但是它看起来像 HTML 结构而不是 JSON。
猜你喜欢
  • 2015-02-02
  • 2011-01-01
  • 1970-01-01
  • 2011-08-20
  • 2012-03-27
  • 2018-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多