将JSON数据从PHP加载到Knockout的问题

时间:2013-12-14 17:34:08

标签: 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
  $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记录,但它没有在页面上显示数据。

3 个答案:

答案 0 :(得分:1)

我可以看到例如

的小错误
  

this.people = ko.observableArray([]);

和其他人你应该重新检查你的代码我认为他们应该是self.people ..... self.person_age,稍后在你的代码中你用自己引用它们,例如这里

  

self.people.push(new personModel(id,   self.person_name(),self.person_age()));

你自称是为什么数据没有加载你没有引用相同的对象人

答案 1 :(得分:0)

我看到你试图根据来自两个来源的代码创建一些东西(你有他们乱码),看起来很相似但很简单(不提供正确的数据)。

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

答案 2 :(得分:-1)

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