Мы делаем сайт с использованием PHP и Knockoutjs. Мы можем отправлять данные JSON с использованием метода $.ajax
в Knockoutjs.
Но это не загрузка первоначально запрошенных данных.
PHP-код
$students = $db->query("SELECT * FROM students WHERE status = 1");
$students_r = array();
while($row = $students->fetch_array()){
//default student data
$id = $row['id'];
$name = $row['name'];
$age = $row['age'];
//update status
//its false by default since
//this is only true if the user clicks
//on the span
//$name_update = false;
// $age_update = false;
//build the array that will store all the student records
$students_r[] = array(
'id' => $id, 'name' => $name, 'age' => $age,
);
}
echo json_encode($students_r); //convert the array to JSON string
и это фактически генерирует правильные данные json
[
{"id":"1","name":"monkey d. luffy","age":"15"},
{"id":"4","name":"son goku","age":"30"},
{"id":"5","name":"naruto uzumaki","age":"16"},
{"id":"6","name":"draco","age":"15"},
{"id":"10","name":"NIklaus MikaelSon","age":"1500"},
{"id":"16","name":"Elijah","age":"1000"},
{"id":"19","name":"Chitrank","age":"23"},
{"id":"20","name":"Rahul","age":"24"}
]
Теперь Knockout входит в игру, чтобы показать эти данные на странице. Итак, вот HTML-страница
function RefreshUser(data) {
this.name = ko.observable(data.name);
this.age = ko.observable(data.age);
};
var personModel = function(id, name, age){
var self = this; //caching so that it can be accessed later in a different context
this.id = ko.observable(id); //unique id for the student (auto increment primary key from the database)
this.name = ko.observable(name); //name of the student
this.age = ko.observable(age);
this.nameUpdate = ko.observable(false); //if the name is currently updated
this.ageUpdate = ko.observable(false); //if the age is currently updated
//executed if the user clicks on the span for the student name
this.nameUpdating = function(){
self.nameUpdate(true); //make nameUpdate equal to true
};
//executed if the user clicks on the span for the student age
this.ageUpdating = function(){
self.ageUpdate(true); //make ageUpdate equal to true
};
};
var model = function(){
var self = this; //cache the current context
this.person_name = ko.observable(""); //default value for the student name
this.person_age = ko.observable("");
this.person_name_focus = ko.observable(true); //if the student name text field has focus
this.people = ko.observableArray([]); //this will store all the students
this.createPerson = function(){
if(self.validatePerson()){ //if the validation succeeded
//build the data to be submitted to the server
var person = {'name' : this.person_name(), 'age' : this.person_age()};
//submit the data to the server
$.ajax(
{
url: 'refresher_save.php',
type: 'POST',
data: {'student' : person, 'action' : 'insert'},
success: function(id){//id is returned from the server
//push a new record to the student array
self.people.push(new personModel(id, self.person_name(), self.person_age()));
self.person_name(""); //empty the text field for the student name
self.person_age("");
}
}
);
}else{ //if the validation fails
alert("Name and age are required and age should be a number!");
}
};
this.validatePerson = function(){
if(self.person_name() !== "" && self.person_age() != "" && Number(self.person_age()) + 0 == self.person_age()){
return true;
}
return false;
};
$.getJSON("refresher_save.php", function(userModels) {
var t = $.map(userModels.people, function(item) {
console.log("Something");
return new RefreshUser(item);
});
self.people(t);
});
this.removePerson = function(person){
$.post(
'refresher_save.php',
{'action' : 'delete', 'student_id' : person.id()},
function(response){
//remove the currently selected student from the array
self.people.remove(person);
}
);
};
this.updatePerson = function(person){
//get the student details
var id = person.id();
var name = person.name();
var age = person.age();
//build the data
var student = {'id' : id, 'name' : name, 'age' : age};
//submit to server via POST
$.post(
'refresher_save.php',
{'action' : 'update', 'student' : student}
);
};
};
ko.applyBindings(new model());
Теперь мы используем $.getJSON
для извлечения всех записей JSON, но он не отображает данные на странице.
например, я вижу небольшие ошибки
this.people = ko.observableArray([]);
и другие вы должны перепроверить свой код, я думаю, что они должны быть self.people..... self.person_age, позже в вашем коде вы ссылаетесь на них, например, здесь
self.people.push (новый человекModel (id, self.person_name(), self.person_age()));
вы ссылаетесь на себя, поэтому данные не загружаются, вы не ссылаетесь на тех же людей объекта
Я вижу, вы пытались создать что-то на основе кода из двух источников (у вас есть скремблирование), которые выглядят одинаково, но простые не то же самое (не предоставляют правильные данные).
Сначала вы создаете логическую двуличность с помощью RefreshUser()
и personModel()
. Вы должны оставить только personModel()
как
var personModel = function(data){
var self = this;
this.id = ko.observable(data.id);
this.name = ko.observable(data.name);
this.age = ko.observable(data.age);
/* all the rest stays the same */
Затем в createPerson()
вы должны обновить эту строку
self.people.push(new personModel(person));
Тогда окончательная часть $.getJSON
должна выглядеть так:
$.getJSON("refresher_save.php", function(allData) {
var data = $.map(allData, function(item) { return new personModel(item) });
self.people(data);
});
и должен располагаться в нижней части представления model()
.
Спасибо за ваше время, но моя проблема была решена, на самом деле в моем php-скрипте я передавал неиспользуемые параметры, которые вызывают проблему, когда я удалял эти параметры, работал и значения базы данных загружались при обновлении страницы. Спасибо за ваши ответы. :)
var self = this;
это общий шаблон проектирования, они могут отличаться в зависимости от контекста, но вы не можете сказать, что это происходит из-за имени переменной