【问题标题】:Issue with Loading JSON data from PHP to Knockout将 JSON 数据从 PHP 加载到 Knockout 的问题
【发布时间】:2014-01-02 09:15:55
【问题描述】:

我们正在使用 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 记录,但它没有在页面上显示数据。

【问题讨论】:

    标签: php jquery json knockout.js


    【解决方案1】:

    例如,我可以看到一些小错误

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

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

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

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

    【讨论】:

    • var self = this; 这是一种常见的设计模式,它们可以根据上下文而有所不同,但你不能因为变量名而说它们这样做
    • 好的,但是 self =this;不是问题,我们使用这个是为了让knockout的函数和javascript的函数之间不会发生冲突,我猜。
    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2013-03-08
        • 2020-09-09
        • 2015-02-14
        • 2014-07-05
        • 2012-07-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多