如何将json对象从jsp返回到angularjs ajax http.get?

时间:2015-07-20 04:48:08

标签: json angularjs jsp

当我运行jsp文件时,我得到[{“USRNM”:“sahar”,“USRPWD”:“password”}]这是正确的,但是当我运行html时,我无法显示数据,当我发出警报时,我得到了当我尝试使用json文件时,html标签内的数据以[对象对象]的形式警告数据。请帮助我找出我做错了什么。

JSP:

    Statement stmt = con.createStatement();

    ResultSet rs = stmt.executeQuery("select UsrNm,UsrPwd from dbo.tblUsr"); 


    ResultSetMetaData rsMetaData = rs.getMetaData();

    int numberOfColumns = rsMetaData.getColumnCount();
    JSONArray jsonArray = new JSONArray();
    //List <JSONObject> jsonArray = new ArrayList<JSONObject>();
      List <String> columnNames = new ArrayList<String>();
        for(int i=1;i<=numberOfColumns;i++) {
        columnNames.add(rsMetaData.getColumnName(i).toUpperCase());
    } 
     while(rs.next()) {
         JSONObject obj = new JSONObject();
         for(int i=1;i<=numberOfColumns;i++) {
            String key = columnNames.get(i - 1);
            Object value = rs.getObject(i);
            obj.put(key, value);
         }

    jsonArray.add(obj);
     }

     //response.setContentType("application/json");
       // response.setCharacterEncoding("UTF-8");
       response.getWriter().write(jsonArray.toString());

HTML:

  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
  <body>

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

   <table>
   <tr ng-repeat="x in names">
   <td>{{ x.USRNM}}</td>
   <td>{{ x.USRPWD}}</td>
   </tr>
   </table>
   </div>

   <script>
        var app = angular.module('myApp', []);
        app.controller('customersCtrl', function($scope, $http) {
        $http.get("newjsp2.jsp")
              .success(function (response) {
              // alert(JSON.stringify(response));
              alert(response);
              $scope.names = response;
        }).error(function(response,status,headers,config){
              alert('cannot find resource');
              console.log(response);
              console.log(status);
              console.log(headers);
              console.log(confiq);
         }); 
   });
   </script>

2 个答案:

答案 0 :(得分:0)

尝试使用以下代码,因为我认为从JSP返回的数据是字符串格式,所以在使用Angular JS之前需要将其转换为JSON格式

var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
       $http.get("newjsp2.jsp").success(function (response) {
          $scope.names = JSON.parse(response);
      })
     .error(function(response,status,headers,config){
            alert('cannot find resource');
     }); 
  });

答案 1 :(得分:0)

而不是使用response.getWritter ....我替换了3行并删除了jsp文件中的html标签,所以现在它正常工作:)

   // response.setContentType("json");
      // response.setCharacterEncoding("UTF-8");
   //response.getWriter().write(jsonArray.toString());

       //These 3 lines
       PrintWriter out1 = response.getWriter();
        out1.print(jsonArray);
        out1.flush();