简体   繁体   English

为什么Angular JS $ http.get()在此代码中不起作用?

[英]Why is Angular JS $http.get() not working in this code?

I'm trying to get the RSS feeds from a link. 我正在尝试从链接获取RSS提要。 The ng-click function getNews("SomeText") is working, I have confirmed it with filling a container with some text. ng-click函数getNews("SomeText")正在运行,我已通过在容器中填充一些文本来确认它。 However, $http.get() is not working. 但是, $http.get()无法正常工作。 I only want to show the data for now, I'll parse it later. 我现在只想显示数据,我稍后再解析。

Here is my Angular JS code. 这是我的Angular JS代码。

var app = angular.module("app",[]);
app.controller("newsController", function($scope, $http) {
  $scope.getNews = function(topic) {

    if (topic === "NAmerica") {
    //The program enters this part, I have confirmed, only $http.get() doesn't work
      $http.get('http://www.usnews.com/rss/education')
      .then(function (response) {
        $scope.message = response;

      });
    }
  };
});

My HTML file has this structure: 我的HTML文件具有以下结构:

<html ng-app="app">
   <body ng-controller="newsContainer">
       <a href="#" id="NAmerica" ng-click="getNews('NAmerica')">US &amp; Canada</a>
       <p> {{message}} </p>
   </body>
</html>

As already noted in comments, modern browsers cannot simply request arbitrary URLs via AJAX. 正如评论中已经提到的那样,现代浏览器不能简单地通过AJAX请求任意URL。 This restriction is entirely intentional and called the Same-Origin Policy . 此限制完全是故意的,称为“ 同源策略” By default, browsers can only execute AJAX requests to the same domain that the JavaScript is executed on. 默认情况下,浏览器只能向执行JavaScript的同一域执行AJAX请求。

Usually, there are a few options that you can take. 通常,您可以采取一些选择。

  1. Cross-Domain requests are allowed when the requested site contains a Cross-Origin Resource Sharing (CORS) header in its HTTP response, which usually looks something like this: 当所请求的站点在其HTTP响应中包含跨域资源共享 (CORS)标头时,就允许跨域请求,该标头通常如下所示:

     Access-Control-Allow-Origin: http://yoursite.com 

    Of course, this is only an option when you're in control of the domain that you're requesting content from. 当然,只有在您控制要向其请求内容的域时,这才是一种选择。 If you're executing requests to a 3rd party site, there's usually nothing that you can do about this on your own. 如果您要执行对第三方网站的请求,那么通常您自己无能为力。

    Btw, you should also be able to see a respective error message in your browser console. 顺便说一句,您还应该能够在浏览器控制台中看到相应的错误消息。

  2. Request the foreign content using a server-side script on your domain, for instance using a PHP or [insert random server-side scripting language here] script on your server that you then request via AJAX. 使用您的域名的服务器端脚本,例如使用PHP或[此处插入随机的服务器端脚本语言] 你的服务器,你然后通过Ajax请求对剧本要求外国内容。 That way, you can work around the Same-Origin Policy, since the user's browser can now request a resource on your own domain. 这样,您可以解决“同源策略”,因为用户的浏览器现在可以在您自己的域上请求资源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM