【问题标题】:XMLHttpRequest cannot load in angularjsXMLHttpRequest 无法在 angularjs 中加载
【发布时间】:2015-03-16 00:23:38
【问题描述】:

我正在向这个site学习。

我将它用于 Android 应用程序以获取 PHP 数据并显示应用程序。

当我在 AngularJS 中启动 web 服务时,谷歌浏览器在控制台中给出了这个错误:

XMLHttpRequest 无法加载 http://192.168.1.10/android_connect/JsonReturn.php。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,Origin 'null' 不允许访问。

这是我的 JavaScript 代码:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script>function GetUsers($scope, $http) {
    // this is where the JSON from api.php is consumed
    $http.get('http://192.168.1.10/android_connect/JsonReturn.php').
        success(function(data) {
            // here the data from the api is assigned to a variable named users
            $scope.users = data;
        });
}</script>

然后我设置HTML代码:

<div ng-controller="GetUsers">

<table>
<thead><tr><th>ID</th><th>Name</th><th>Email</th></tr></thead>
<tbody>
<tr ng-repeat="user in users"><td>{{user.id}}</td><td>{{ user.name }}</td><td>{{user.email}}</td></tr>
</tbody>
</tfoot></tfoot>
</table>

</div>

我尝试了发布的所有可能的解决方案,但似乎无法解决我的代码中的问题。

【问题讨论】:

  • 我认为错误几乎是不言自明的没有'Access-Control-Allow-Origin' header is present on the requested resourceAccess-Control-Allow-Origin 应该在您的标题中
  • 我添加了这个但不起作用

标签: javascript php angularjs google-chrome xmlhttprequest


【解决方案1】:

您正在尝试使用 XMLHttpRequest 进行跨域请求。为此,响应请求的 Web 服务器需要将 Access-Control-Allow-Origin 响应标头设置为 *

【讨论】:

  • 在你的 JsonReturn.php 中添加 header('Access-Control-Allow-Origin: *');
【解决方案2】:

或者,从托管 API 的同一服务器提供 Angular 页面。那你就没有跨域请求了。

【讨论】:

    猜你喜欢
    • 2016-09-06
    • 2017-04-28
    • 2011-11-01
    • 1970-01-01
    • 2023-04-10
    相关资源
    最近更新 更多