gpt4 book ai didi

javascript - 我已经完成了 AngularJS 代码,但数据没有显示

转载 作者:行者123 更新时间:2023-11-28 06:24:31 25 4
gpt4 key购买 nike

请帮助我找到我的编码问题,我已经完成了所有 AngularJS 代码以及 json 编码的 html 和 php,但我无法获取数据库中的数据...这是我当前的代码

索引.html

 <body ng-app="myApp" ng-controller="KaryawanCtrl">

<form method="post">
<input type="text" ng-model="karyawan.nama">
<input type="text" ng-model="karyawan.alamat">
<input type="submit" ng-click="tambahData()" value="simpan">
</form>
<table ng-init="dapatkanData()">
<thead>
<th>nama</th>
<th>alamat</th>
</thead>
<tr ng-repeat="item in dataKaryawan">
<td>{{item.nama}}</td>
<td>{{item.alamat}}</td>
</tr>
</table>

这是 Angular 代码

js/app.js

 var app= angular.module("myApp",[]);
app.controller("KaryawanCtrl",function($scope,$http){
//variabel awal
$scope.aksi="tambah";
$scope.karyawan={};
//angularjs untuk menyimpan data ke database
$scope.tambahData = function(){
$http.post(
'post.php',
{
data: $scope.karyawan
}
).success(function(data){
alert("data berhasil dimasukkan");
}).error(function(){
alert("Gagal menyimpan data");
});

//angularJS untuk menampilkan data ke tabel
$scope.dapatkanData = function(){
$http.get('karyawan.php').success(function(data){
$scope.dataKaryawan = data;
});
};

};
});

这是 php

$koneksi = mysqli_connect("localhost","root","","belajar") or die("tidak bisa tersambung ke database");
$perintah_sql = "SELECT * FROM karyawan";

$data = [];
$result = mysqli_query($koneksi,$perintah_sql);

while($row= mysqli_fetch_array($result)){
$temp_data = [];
$temp_data['nama']= $row['nama'];
$temp_data['alamat']=$row['alamat'];
array_push($data,$temp_data);
}

echo json_encode($data);

最佳答案

问题是您的 dapatkanData 函数是在 tambahData 函数内部定义的。只需像这样将其移到外面,它就应该可以工作:

var app= angular.module("myApp",[]);

app.controller("KaryawanCtrl",function($scope,$http){
//variabel awal
$scope.aksi="tambah";
$scope.karyawan={};

$scope.tambahData = function(){
$http.post('post.php',{ data: $scope.karyawan }).success(function(data){
alert("data berhasil dimasukkan");
}).error(function(){
alert("Gagal menyimpan data");
});
};

$scope.dapatkanData = function(){
$http.get('karyawan.php').success(function(data){
$scope.dataKaryawan = data;
});
};

$scope.dapatkanData(); // Use this instead of ng-init. Remove that from the html
});

关于javascript - 我已经完成了 AngularJS 代码,但数据没有显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35243319/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com