我是angularjs的新手,我正在做基本演示,因为我使用php和angularjs服务将数据插入数据库并将其传递给控制器,数据插入数据库但是在控制台日志中出现错误。任何人都可以帮我解决这个错误吗?
var app = angular.module('myApp', [])
//controller
app.controller("myController",['$scope','StringServices', function($scope,StringServices){
$scope.User= {};
$scope.insert = function(User){
StringServices.insertString($scope.User, function(response){
if(response.FLAG === "_SUCCESS"){
console.log('Success');
}
else{
console.log('Error');
}
}).error(function(error){
console.error(error);
});
}
}])
//services
app.factory('StringServices', function($http){
return {
insertString: function(User){
var data = {name: User.name};
$http.post('http://localhost/anjali_services/server/insert.php',data)
.success(function(response){
return response;
});
}
};
});
<table>
<tr>
<td>Your Name</td>
<td><input type= "text" ng-model="User.name"></td>
</tr>
<tr>
<td></td>
<td><input type="button" ng-click="insert(User)" value="Insert"></td>
</tr>
</table>
<?php
$db = new PDO("mysql:host=localhost;dbname=anjali;port=3306","root","");
$data = json_decode(file_get_contents("php://input"));
$name = $data->name;
$resp = array();
$q = "INSERT INTO udata (name) VALUES (:name)";
$query = $db->prepare($q);
$execute = $query->execute(array(
":name" => $name
));
if($execute == true){
$resp['FLAG'] = "_SUCCESS";
print json_encode($resp);
}else{
echo "ERROR";
}
?>
答案 0 :(得分:1)
我必须说我无法立即找出问题的根源,但我建议您至少从服务中返回$http
承诺并使用then/catch
处理结果。至少我发现这更容易阅读和阅读了解发生了什么。
无论如何,以这种方式修改你的例子似乎工作得很好。无论如何,反对模拟REST服务。
<强> HTML 强>
<body ng-controller="myController as vm">
Your Name:
<input type= "text" ng-model="User.name">
<input type="button" ng-click="insert(User)" value="Insert">
</body>
<强>的JavaScript 强>
var app = angular.module('myApp', [])
.controller('myController', function($scope, StringServices) {
$scope.User = {};
$scope.insert = function(User) {
StringServices.insertString(User)
.then(function(response) {
console.log('ok', response);
})
.catch(function(error) {
console.log('failed', error);
});
};
})
.factory('StringServices', function($http){
return {
insertString: function(User){
return $http.post('https://httpbin.org/post', { name: User.name });
}
};
});
此处相关的plunker https://plnkr.co/edit/MVUSeg
答案 1 :(得分:-2)
StringServices中的insertString函数只接受一个User参数,但是在控制器中传递两个参数,即User和一个函数。因此没有带两个参数的函数insertString。
你可以这样:
var app = angular.module('myApp', [])
//controller
app.controller("myController",['$scope','StringServices', function($scope,StringServices){
$scope.User= {};
$scope.insert = function(User){
StringServices.insertString($scope.User, function(response){
if(response.FLAG === "_SUCCESS"){
console.log('Success');
}
else{
console.log('Error');
}
});
}
}])
//services
app.factory('StringServices', function($http){
return {
insertString: function(User, callbackFn){
var data = {name: User.name};
$http.post('http://localhost/anjali_services/server/insert.php',data)
.success(callbackFn);
}
};
});