我正在尝试做一些Web项目,包括AngularJS前端和SlimPHP后端之间的通信。
我想在php脚本中调用查询并生成JSON对象,以便在我的前端MVC中使用
这是我的php脚本的一部分,使用Slim php框架$app->get('/users','getUsers');
$app->run();
// GET http://www.yourwebsite.com/api/users
function getUsers() {
$sql = "SELECT user_id,username,name,profile_pic FROM users ORDER BY user_id DESC";
try {
$db = getDB();
$stmt = $db->query($sql);
$users = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode($users);
} catch(PDOException $e) {
//error_log($e->getMessage(), 3, '/var/tmp/phperror.log'); //Write error log
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
在Angular的控制器中,这个表达式不能正常工作
$http.jsonp("localhost/users).success(function (data) {
$scope.myusers = data.results;
}
)
我应该在我的php脚本改变什么?在浏览器中,当我输入http://localhost/users
您正在使用仅用于跨域json with padding
请求的$http.jsonp()
。这些不是常规的ajax请求,它们实际上是脚本请求,需要一个特殊的外部包装函数调用。
对于正常的json GET请求使用$http.get()
$http.get("localhost/users").success(function (data) {
$scope.myusers = data.results;
});