我正在尝试使用angularjs将数据从前端插入mysql db。但是即使没有错误消息,它也不会插入到数据库中。以下是我使用的代码。
索引.html
<html ng-app="demoApp">
<head>
<title> AngularJS Sample</title>
<script src="js/angular.min.js"></script>
<script src="js/angular-route.min.js"></script>
<script type="text/javascript" src="js/script.js"></script>
</head>
<body>
<div class="container" ng-view>
</div>
</body>
</html>
脚本.js
demoApp.config( function ($routeProvider,$locationProvider) {
$routeProvider
.when('/',
{
controller: 'SimpleController',
templateUrl: 'Partials/view1.html'
})
.when('/view2',
{
controller: 'SimpleController',
templateUrl: 'Partials/view2.html'
})
.otherwise({redirectTo: '/'});
});
demoApp.controller('SimpleController',function ($scope,$http){
$http.post('server/view.php').success(function(data){
$scope.friends = data;
});;
$scope.addNewFriend = function(add){
var data = {
fname:$scope.newFriend.fname,
lname:$scope.newFriend.lname
}
$http.post("server/insert.php",data).success(function(data, status, headers, config){
console.log("inserted Successfully");
});
$scope.friends.push(data);
$scope.newFriend = {
fname:"",
lname:""
};
};
});
视图1.html
<div class="container" style="margin:0px 100px 0px 500px;">
Name:<input type="text" ng-model="filter.name">
<br/>
<ul>
<li ng-repeat="friend in friends | filter:filter.name | orderBy:'fname'">{{friend.fname}} {{friend.lname}}</li>
</ul>
<br/>
<fieldset style="width:200px;">
<legend>Add Friend</legend>
<form name="addcustomer" method="POST">
First Name:<input type="text" ng-model="newFriend.fname" name="firstname"/>
<br/>
Last Name :<input type="text" ng-model="newFriend.lname" name="lastname"/>
<br/>
<button data-ng-click="addNewFriend()" name="add">Add Friend</button>
</form>
</fieldset>
<a href="#/view2" style="margin:auto;">Next</a>
</div>
以下是我的PHP文件
插入.php
<?php
if(isset($_POST['add']))
{
$firsname=$_POST['firstname'];
$laname = $_POST['lastname'];
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("angularjs") or die(mysql_error());
mysql_query("INSERT INTO friends (fname,lname) VALUES ('$firsname', '$laname')");
Print "Your information has been successfully added to the database.";
}
?>
我知道我在这里做了一些愚蠢的事情。我今天刚开始学习angularjs。当我尝试使用纯 HTML 插入 PHP 代码以插入数据库时,它运行良好。我不明白我在这里做错了什么。希望有人能在这里帮助我
插入数据的脚本是错误的。将其替换为以下内容
$http.post("server/insert.php",{'fstname': $scope.newFriend.fname, 'lstname': $scope.newFriend.lname})
.success(function(data, status, headers, config){
console.log("inserted Successfully");
});
并按如下方式更改 PHP。
$data = json_decode(file_get_contents("php://input"));
$fstname = mysql_real_escape_string($data->fstname);
$lstname = mysql_real_escape_string($data->lstname);
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("angularjs") or die(mysql_error());
mysql_query("INSERT INTO friends (fname,lname) VALUES ('$fstname', '$lstname')");
Print "Your information has been successfully added to the database.";
当我尝试使用您的代码时,这对我有用。