【问题标题】:Error with http request to PHP fiile angular [duplicate]对PHP文件角度的http请求出错[重复]
【发布时间】:2018-11-12 22:20:17
【问题描述】:

我正在尝试向我的 php 文件发出 http 请求。但它返回给我以下错误

可能未处理的拒绝:{"data":null,"status":-1,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null], "jsonpCallbackParam":"callback","url":"localhost/sample.php","headers":{"Accept":"application/json, text/plain, /"}}, "statusText":"","xhrStatus":"error"}

我的角度要求是

var some = angular.module("first_module", [])
            .controller("first_controller", function($scope, $http, $log) {
    $http.get('localhost/sample.php').then(function(response) {
                    $scope.students = response;
                    $log.info();
        });
});

我的 PHP 文件是

<?php
$var2 = new stdClass();
$var2->name = 'john';
$var2->class = '7';
$var2->fee = '45000';
$var2->point = '5';
$response[0] = $var2;
$var2->name = 'ahmed';
$var2->class = '7';
$var2->fee = '55600';
$var2->point = '2';
$response[1] = $var2;
echo json_encode($response);
?>

我什至无法理解错误。在此先感谢

更新: 在为失败添加另一个功能并在控制台中打印日志时,我收到以下错误

var some = angular.module("first_module", [])
            .controller("first_controller", function($scope, $http, $log) {
    $http.get('localhost/sample.php').then(function(response) {
                    $scope.students = response;
                    $log.info();
        }, function(err) {
                      console.log($log.info);
         });
});

这是我收到的错误

【问题讨论】:

  • 我没有使用过 php 调用,但我认为你应该从 $http 中删除 localhost。可以分享一下控制台报错截图吗
  • 感谢您的回复,但我在删除 localhost 时也收到同样的错误
  • 分享控制台报错截图。
  • 感谢@Shashank Vivek 的回复并用图片更新了它
  • -1 状态通常表示 CORS 问题。

标签: php angularjs http


【解决方案1】:

我认为你应该采取更安全的方法:

在浏览器中测试你的 URL,

Http(s)://localhost/sample.php

如果浏览器返回您的结果并且一切正常,则在您的代码中使用完整的 URL。 (通过此测试,您正在测试您的服务器是否正在运行,并且 .php 文件以 json 形式返回预期值。)

$http.get('http://localhost/sample.php') 

或者,如果您确定您的文件在哪个相对路径上。就像执行同一文件夹中的所有文件一样。

$http.get('sample.php')

【讨论】:

  • 我的 sample.php 在 ubuntu 系统的 apache 服务器上,即在目录 /var/www/html/ 中,但我的 angular 文件在桌面中。我找不到任何错误原因?不过感谢您的回答。并且 url localhost/sample.php 完美地打印了 json 数据。
  • 您还需要在服务器上运行 Angular。您可以获得域跨脚本错误。尝试将您的 Angular 应用程序放在子文件夹 .../html/app 中,然后使用 localhost/app/angular.html
猜你喜欢
  • 2018-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-29
  • 1970-01-01
  • 2022-01-01
相关资源
最近更新 更多