【问题标题】:Angular JS $http.get does not receive data from PHP scriptAngular JS $http.get 不接收来自 PHP 脚本的数据
【发布时间】:2014-08-17 00:52:18
【问题描述】:

我正在使用 Angular 的 $http.get 函数来调用 PHP 脚本文件来检索数据

var $promise = $http.get("../php-bin/example.php",obj).success(function(data) {

              console.log(data);
            });

php 应该只是从 mysql 数据库中获取数据以找出将数据获取到我的应用程序的方法

$user = json_decode(file_get_contents('php://input'));
$email = $user->email;
$pass = $user->pass;

$con = //a mysql_connection;
// Check connection
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error(); 
}

$validateEmail = "SELECT `Email` FROM `newUsers` WHERE `Email` = '$email' ";

if ($result = mysqli_query($con,$validateEmail)) {
     if ($result->num_rows == 1){
        $date = '2014-08-13'; 
        //$sql = "INSERT INTO newUsers (Email, CreationDate, UserRef, Type, id) VALUES ('$email','$date','$email','Host','$ssid')";
        $sql = "SELECT `email` FROM `newUsers` WHERE `hashpass` = '$pass' ";

        $result = mysqli_query($con,$sql);

        $row = mysqli_fetch_assoc($result);

        return $row;
        //I never receive this data in the angular app.
    } 
}
mysqli_close($con);
?>

有人能给我指出正确的方法吗?

【问题讨论】:

    标签: javascript php mysql angularjs


    【解决方案1】:

    我看到你有一个 return 声明而不是 echo 声明。 return 语句不会打印在 PHP 输出中。 A return statement outside a function has only sense when you include the file:

    $returned = include('the_file_you_showed_here.php');
    //you will hold the row here
    

    return 语句 kills the current script 返回包含器脚本(如果有),但不向输出发送任何值(这就是 die/exit 的目的)。你应该:

    1. return 更改为echo
    2. 如果您打算发送 json 数据,请记住在任何实际的 echo 指令或非 PHP 内容之前发送 header('Content-type: application/json')
    3. 记得对数据进行编码:return json_encode($row)

    【讨论】:

    • 感谢您的回复。我编辑了 return 语句,但这并不是我的代码唯一有问题的地方。当正确的方法是 $http.get('url'); 时,我正在调用 $http.get('url',obj);我这样做是因为我试图发送一个对象来匹配后端的结果。
    • 我认为这样的对象有表示连接参数的意图。
    【解决方案2】:

    确保在您的 php 中回显您的结果,回显的结果会传递到您的变量中

    例如,如果你从你的作用域传入一个变量,比如

    function($scope,$http){
    
    $scope.obj= "your variable";
    
    $reuslt = http.get('yourlocation/yourfile.php?val='+obj');
    

    你的 php 脚本

    <?
    $value = $_GET['val']
    
    
    //not your variables have been passed in and you can use it to do your custom function wich ever way you like
    and echo your result after wards
    ?>
    

    希望对你有帮助

    【讨论】:

      【解决方案3】:

      你不能这样调用相对路径。该文件必须存在于公共目录或更低的目录中。例如,如果您的所有文件都在 /home/yourname/public 中,则需要调用 /php-bin/example.php,其中 php-bin 位于公共目录 (/home/yourname/public/php-bin) 中.

      【讨论】:

      • PHP 文件工作并被执行,我知道这一点,因为当我插入数据库中的表时,我会做同样的事情。
      • 我看到你说你解决了你的问题。为了确保,你是说你用../php-bin/example.php来调用它?
      • 是的,因为我的结构如下。 www/ -js -css -php-bin -project/ 文件调用 ../php-bin/file.php 这里
      猜你喜欢
      • 2016-03-19
      • 2022-11-04
      • 1970-01-01
      • 2016-10-02
      • 1970-01-01
      • 2015-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多