javascript XMLHttpRequest 无法在 angularjs 中加载
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28000198/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
XMLHttpRequest cannot load in angularjs
提问by Deepak Acharya
I am learning from this site.
我正在从这个网站学习。
I use this for an Android application to fetch the PHP data and show the application.
我将它用于 Android 应用程序以获取 PHP 数据并显示该应用程序。
When I start the web service in AngularJS, Google Chrome gives this error in the console:
当我在 AngularJS 中启动 web 服务时,谷歌浏览器在控制台中给出了这个错误:
XMLHttpRequest cannot load http://192.168.1.10/android_connect/JsonReturn.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
XMLHttpRequest 无法加载http://192.168.1.10/android_connect/JsonReturn.php。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许访问 Origin 'null'。
This is my JavaScript code:
这是我的 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>
Then I set the HTML code:
然后我设置 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>
I tried all the possible solutions posted, but it doesn't seem to fix the issue in my code.
我尝试了所有可能的解决方案,但它似乎没有解决我的代码中的问题。
回答by jrossi
You are trying to make a cross domain request using XMLHttpRequest. For that to work, the web server responding to the request needs to have the Access-Control-Allow-Origin
response header set to *
.
您正在尝试使用 XMLHttpRequest 进行跨域请求。为此,响应请求的 Web 服务器需要将Access-Control-Allow-Origin
响应标头设置为*
。
回答by PhiLho
Alternatively, serve the Angular page from the same server than hosting your API. Then you don't have a cross-domain request.
或者,从托管 API 的同一服务器提供 Angular 页面。那么你就没有跨域请求。