如何在 AngularJS 中使用 $http.get 从 jsp 页面获取响应?
Posted
技术标签:
【中文标题】如何在 AngularJS 中使用 $http.get 从 jsp 页面获取响应?【英文标题】:How to get a response from a jsp page using $http.get in AngularJS? 【发布时间】:2018-02-25 22:52:50 【问题描述】:我是 AngularJS 中 JSON 和 $http 服务的新手。我正在尝试从 jsp 文件(位于同一文件夹中)获得响应。但是当我在服务器上运行它时,什么也没有打印出来。也没有错误。
请有人帮忙。非常感谢您在此问题上的时间和帮助。
以下是我使用 AngularJS 的 html 文件:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.5/angular.js"> </script>
<script>
var myApp=angular.module("myApp",[]);
myApp.controller("myController",function($scope,$http)
$http.get("JSON.jsp").then(function(response)
$scope.array=response;
).then(function(error)
console.log(error, 'can not get data.');
);
);
</script>
<meta charset="ISO-8859-1">
<title>AngularCheck</title>
</head>
<body ng-controller="myController" >
<div ng-repeat="arr in array">
arr.name
arr.age
</div>
</body>
</html>
下面是我的jsp文件:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>JSON page</title>
</head>
<body>
<%
out.println(" [\"name\":\"jothi\",\"age\":\"20\",\"name\":\"Guru\",\"age\":\"22\"]");
%>
</body>
</html>
【问题讨论】:
若要获得更有意义的回复,请同时发布完整的错误消息。 @jan.vdbergh "也没有错误。" @jdgregson 首先我使用了 .then(function())。将其更改为 .catch 后没有错误。但是当我在服务器上运行它时仍然没有打印任何内容。 【参考方案1】:你需要使用catch
而不是then
来获取错误信息
$http.get("JSON.jsp").then(function(response)
$scope.array=response.data;
).catch(function(error)
console.log(error, 'can not get data.');
);
【讨论】:
谢谢萨奇拉。我已经改变它来捕捉。但是网页上仍然没有打印任何内容。 '$scope.array' 对象中似乎没有存储任何内容。 您需要访问data
属性。改变它$scope.array=response.data
先生,即使将其更改为 '$scope.array=response.data' ,结果也是一样的。你能在你的机器上运行这段代码并分享结果吗?以上是关于如何在 AngularJS 中使用 $http.get 从 jsp 页面获取响应?的主要内容,如果未能解决你的问题,请参考以下文章
AngularJS + JQuery:如何在 angularjs 中获取动态内容