2016-10-17 30 views
0

我试图从URL获取JSON文本流(例如SOMEURL/ean.php?id = 4001513007704)。结果是这样的:通过AngularJS从外部URL获取文本

{ 
 
    "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>

这并不(可变留空)。在这种情况下,我使用谷歌,但通常我们会使用其他来源!

<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中的数据?有什么解决方法吗?

感谢您的任何帮助!

+0

已经投票决定关闭。 –

回答

1

response.data只会在响应内有data对象时返回。

当你发送一个请求google.com thatyou得到的回应是这样的:

<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,它将会是undefined,因为那里没有数据。如果您点击具有JSON数据的适当终点,您将得到您的回复。

例如,如果您将url更改为https://api.github.com/users/mralexgray/repos,您将看到数据。

+0

不应response.data是否至少从网站返回HTML代码?它不应该是空白的。 – Amiya

+0

回应会。 response.data不会。因为这不是JSON,所以你不能使用点符号 – nikjohn

0

您正在收到此错误,因为您未定义要包含在html中的角度模块。 尝试在该网站的链接http://google.com/运行在W3学校上面的代码所示

<!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://google.com/") 
 
    .then(function(response) { 
 
     $scope.myWelcome = response.data; 
 
    }); 
 
}); 
 
</script> 
 

 
</body> 
 
</html>

enter image description here

+0

嘿!对不起,但我不明白你想告诉我什么。你的屏幕截图也留空了!你能解释一下你在具体的意思吗? – Amiya

+0

屏幕截图描述了当我点击google.com时,它响应成功,然后显示消息,表示它的工作原理 –