我无法使用AngularJs将数据从文本框添加到数据库

时间:2015-07-30 03:48:36

标签: javascript angularjs

<html  ng-app="myApp" >
<head>
    <title>Testing pulling data from php file </title>
    <meta charset='utf-8'>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
    <script>
    var app = angular.module('myApp',[]);
    app.controller('customersCtrl',function($scope,$http){
        $http.get("data.php")
        .success(function(data){
            $scope.names = data;
        });
    });
    </script>
    <style>
    table, td  {
        border: 1px solid grey;
        border-collapse: collapse;
        padding: 5px;
    }
    </style>
</head>

<body>
    Search: <input type="text" ng-model="query"/>
    <table  ng-controller = "customersCtrl"  >
        <tr>
            <th>Name</th>
            <th>Coutry</th>
            <th>City</th>
        </tr>
        <tr ng-repeat="x in names | filter:query| orderBy:'Name'">
            <td>{{x.Name}}</td>
            <td>{{x.Country}}</td>
            <td>{{x.City}}</td>
        </tr>
    </table>

<script>
app.controller('submit',function($scope,$http){
    $scope.submit() = function(){
        $http.post('insertdata.php',{'Name':$scope.firstname,'Country': $scope.country, 'City':$scope.city})
        .success(function(data,status,headers,config){
            console.log("data insert successfully");
        });
    };
});
</script>
<div style="margin-top:150px" >
    <form ng-controller="submit">
        Name:<input type="text" ng-model="firstname"/>
        Country:<input type="text" ng-model="country"/>
        City:<input type="text" ng-model="city"/>
        <input type="submit" value="Add" ng-click="submit()"/>
    </form>
</div>


</body>
</html>



  // insertdata.php
    <?php

        $data = json_decode(file_get_contents("php://input"));

        $name =  mysql_real_escape_string($data->Name); 
        $country = mysql_real_escape_string($data->Country);
        $city = mysql_real_escape_string($data->City);
        $con = mysqli_connect("localhost","root","","mydb");
        $result = mysqli_query($con,"INSERT INTO testing VALUES('$name','$country','$city')");
        Print "Your information has been successfully added to the database."; 


    ?>

代码不会将数据从html添加到数据库 而且我不知道为什么。请帮我纠正代码

1 个答案:

答案 0 :(得分:0)

尝试将$scope.submit() = function(){...}更改为$scope.submit = function(){...}

您可以通过检查浏览器中的网络选项卡来检查请求是否已正确发布到PHP。