Php AngularJS$http.get产品
我在angularjs创建了我的新店。在那里,我有一个名为store的函数,它可以获取我所有的产品。起初我只是在那里写了所有的产品,但现在我想从mysql数据库中获取它们。我认为问题出在$http.get中,但不知道是什么 在我的函数看起来像这样之前:Php AngularJS$http.get产品,php,mysql,angularjs,Php,Mysql,Angularjs,我在angularjs创建了我的新店。在那里,我有一个名为store的函数,它可以获取我所有的产品。起初我只是在那里写了所有的产品,但现在我想从mysql数据库中获取它们。我认为问题出在$http.get中,但不知道是什么 在我的函数看起来像这样之前: function store() { this.products = [ { num: 1, code: 'TEST', category: 'Diverse', name: 'TEST', src: "test.png"
function store() {
this.products = [
{ num: 1, code: 'TEST', category: 'Diverse', name: 'TEST', src: "test.png", description: 'info her', price: 2, cal: 10 }
];
}
这起作用了。我使用$http.get创建了下面的代码,该代码在我的应用商店中没有显示任何内容:
function store() {
$http.get('products.php')
.success(function(data) {
this.products = data;
});
}
My products.php文件对此进行了响应,并将其编码为json:
[{"num":"1","code":"TET","category":"Diverse","name":"Test","src":"test.png","description":"Test","price":"5","cal":"10"}]
products.php文件:
require('scripts/connect.php');
$statement = $conn->prepare("select * from products");
$statement->execute();
while($row = $statement->fetch(PDO::FETCH_ASSOC)){
foreach($row as $key => $value) {
$prod[$key] = $value;
}
$main_arr[] = $prod;
}
$json = json_encode($main_arr);
echo $json;
额外的帮助代码:
controller.js
function storeController($scope, $routeParams, DataService) {
// get store and cart from service
$scope.store = DataService.store;
$scope.cart = DataService.cart;
}
app.js
storeApp.factory("DataService", function () {
// create store
var myStore = new store();
});
确保您已正确地将模块安装到控制器或服务中,无论您如何操作
var myApp = angular.module('myApp',[]);
myApp.controller('storeController', ['$scope', '$http', function($scope, $http) {
$scope.store = {products: getData()};
function getData() {
$http.get('products.php')
.success(function(data) {
return data;
});
}
}]);
控制台中是否有错误?我真的不知道您的代码是如何工作的,但您说此代码工作正常:
function store() {
this.products = [
{ num: 1, code: 'TEST', category: 'Diverse', name: 'TEST', src: "test.png", description: 'info her', price: 2, cal: 10 }
];
}
我假设你有权访问$http
要将上述代码转换为使用$http,应改为如下所示:
function store() {
var self = this;
$http.get('products.php')
.success(function(data) {
self.products = data;
});
}
希望这有帮助。您确定控制器或服务中注入了$http吗?不确定,我该怎么做?您在哪里定义了存储功能!我的store函数在store.js中。我的意思是,您是否在控制器或服务中定义了它!我只是在函数所在的位置插入了代码。这段代码给了我一个错误:错误:store不是一个构造函数如果你把逻辑和一个对象构造函数混合在一起,我会修改我上面的代码以反映一种不同的处理方式。我能问一下你为什么用这个而不是AngularJS的$scope来保存你的数据吗?不知道为什么,从另一个人那里买了这个商店。$scope.store={products:getData};似乎也不起作用:/嗯,这并没有改变错误,仍然是错误:store不是构造函数。我搜索了其他文件,它没有显示任何关于$http的内容。因此我认为没有任何访问权限。然后我无法进一步帮助,除非看到更多的代码。你能在问题中包含更多的代码吗?刚刚编辑,我有更多的代码n文件,但那是购物车和其他东西。现在我刚刚删除了Aaron发送的inject$http代码,我应该把它放在哪里?在我把它放在与我的store函数相同的文件中之前,不知道这是否会改变什么?angularjs的版本是1.1.5,你认为是因为这个吗?不,这与angularjs的版本无关,bu如果你还没有解决这个问题,我会在有时间的时候再看一看你的代码。