将JSON数据从PHP加载到Knockout时出现问题

将JSON数据从PHP加载到Knockout时出现问题,php,jquery,json,knockout.js,Php,Jquery,Json,Knockout.js,我们正在使用PHP和Knockoutjs制作一个网站。我们可以使用Knockoutjs中的$.ajax方法发送JSON数据 但它并没有加载最初请求的数据 PHP代码 $students = $db->query("SELECT * FROM students WHERE status = 1"); $students_r = array(); while($row = $students->fetch_array()){ //default student data $i

我们正在使用PHP和Knockoutjs制作一个网站。我们可以使用Knockoutjs中的
$.ajax
方法发送JSON数据

但它并没有加载最初请求的数据

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.observearray([])

其他人你应该重新检查你的代码,我认为他们应该是自我的。。。。。self.person\u age,稍后在代码中,您将使用self引用它们,例如这里

self.people.push(新人物模型), self.person_name(),self.person_age()


你用self引用数据这就是为什么没有加载数据你没有引用同一个对象人们

谢谢你的时间,但我的问题已经解决了,实际上在我的php脚本中,我传递了未使用的参数,这导致了问题,当我删除这些参数时,它工作正常,并且在页面刷新时加载了数据库值。谢谢您的回复。:)

我看到您试图根据两个源的代码创建一些东西(您将它们置乱),它们看起来相似,但简单却不相同(没有提供正确的数据)

首先,使用
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()
视图的底部。

var self=this这是一种常见的设计模式,它们可以根据上下文的不同而有所不同,但不能因为变量名而说它们是不同的好吧,但self=this;这不是问题所在,我想我们使用它是为了在knockout的函数和javascript的函数之间不会发生冲突。