Angular $ http.get并没有返回我的预期

时间:2017-07-06 08:30:00

标签: php webserver

我试图做一个简单的http get请求,但它没有返回我的预期。

这是代码

.js:

$http.get("database.php").success(function(data, status)
{
    alert(data);
    $scope.data = data;
}
).error(function(data, status)
{
    $scope.untruc = "Error";
});

.php:

<?php
header('Content-type: application/json');

$conn = // my connection

// Check connection
if ($conn->connect_error)
    echo "Connection failed";
else
{
    $sql = "SELECT id FROM user";
    $result = $conn->query($sql);
    echo json_encode($result);
}

&GT;

,输出是:

data : <?php header('Content-type: application/json'); $conn = // my connection; // Check connection    if ($conn->connect_error) echo "Connection failed"; else { $sql = "SELECT id FROM user"; $result = $conn->query($sql); echo json_encode($result); } ?>

文字代码......

我希望它能获得$结果。你知道我怎么做吗?

1 个答案:

答案 0 :(得分:1)

请检查一下php代码。 并尝试实现此代码

<?php
header('Content-type: application/json');

$conn = new mysqli('localhost', 'root', 'password', 'database');

// Check connection
if ($conn->connect_error)
    echo "Connection failed";
else
{
    $sql = "SELECT * FROM users";
    $result = $conn->query($sql);
    $myresult = [];
    $i =0;
    while($row = $result->fetch_array()) {
		$myresult[$i] = $row;
		$i++;
	}
    
    //echo "<pre>";
    echo json_encode($myresult);
}

?>