我正在尝试从 URL 获取 JSON-Text-Stream(例如 SOMEURL/ean.php?id=4001513007704)。结果如下所示:
{
"product": {
"ean_id": "4001513007704",
"title": "Gerolsteiner Mineralwasser",
...
},
"success": true
}
如您所见,这些是扫描项目的一些信息。 我使用 URL (--> http://www.w3schools.com/angular/tryit.asp?filename=try_ng_http_get ) 搜索实现,此示例仅适用于内部 URL。 Google 和其他来源将该变量留空。
这确实有效。它返回输入网站的 HTML 代码:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<p>Today's welcome message is:</p>
<h1>{{myWelcome}}</h1>
</div>
<p>The $http service requests a page on the server, and the response is set as the value of the "myWelcome" variable.</p>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("http://www.w3schools.com/angular/default.asp")
.then(function(response) {
$scope.myWelcome = response.data;
});
});
</script>
</body>
</html>
这不是(变量留空)。在本例中,我使用 Google,但通常我们会使用其他来源!
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("http://google.com/")
.then(function(response) {
$scope.myWelcome = response.data;
});
});
</script>
我认为这是由于网站的安全设置所致。
如何从 URL 获取数据?有什么解决办法吗?
感谢您的帮助!
最佳答案
response.data
仅当响应中有 data
对象时才会返回某些内容。
向 google.com
发送请求时收到的响应如下:
<TITLE>302 Moved</TITLE></HEAD><BODY>
<H1>302 Moved</H1>
The document has moved
<A HREF="https://www.google.co.in/">here</A>.
</BODY></HTML>
这是因为该 URL 提供 HTML,而不是某些 JSON 响应。
如果您对此执行response.data
,它将是未定义的,因为那里没有数据。如果您到达具有 JSON 数据的正确端点,您将收到响应。
例如,如果您将网址更改为 https://api.github.com/users/mralexgray/repos
,您将看到数据。
关于javascript - 通过 AngularJS 从外部 URL 获取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40084296/