使用MySQL&amp ;;检索数据Backbone JS

时间:2013-04-04 20:10:54

标签: php mysql backbone.js

我希望你能帮助我。我正在尝试使用mysql和backbone从我的数据库中获取数据。 问题是我可以创建一个«用户»,我可以得到所有这些。但是,当我试图做出:

var user = new User({id: 10});

我总是有这种类型的结果,取决于给定的id:

Object {id: "10", nom: "", age: "", prenom: ""}

但是我收到了服务器的回复:

[{"id":"10","nom":"test","prenom":"test","age":"12"}]

因此,执行GET请求,并返回未保存在«user»变量中的内容。

有关更多说明,请参阅我的脚本

// The model
var User = Backbone.Model.extend({
    defaults: {
        id:"",
        nom:"",
        age:"",
        prenom:""
    },

    url: function(){
    if (this.isNew()){
      return "./users.php";
    } else {
      return "./users.php?id=" + this.id;
    }
  }
});

// The collection
var Users = Backbone.Collection.extend({
    models:"user",
    url:"./users.php"
});

// The view
var EditUser = Backbone.View.extend({
    el: ".page",
    render: function(options) {
        var that = this
        if (options.id) {
            var user = new User({id: options.id});
            console.log(user.toJSON());
            user.fetch({
                success: function(user){
                    var template = _.template($('#edit-user-template').html(), {user: user});                   
                    that.$el.html(template);
                }
            })
        } else {
            var template = _.template($('#edit-user-template').html(), {user:null});
            this.$el.html(template);
        }

    },
    events: {
        'submit .edit-user-form' : 'saveUser',
    },

    saveUser: function(ev){
        data = $(ev.currentTarget).serializeObject();
        var user = new User();
        user.save(data, {
            success: function(user) {
                router.navigate('', {trigger:true})
            }
        });
        return false;
    }
});

我的users.php

<?php 

    $request_method = strtolower($_SERVER['REQUEST_METHOD']);


    switch($_SERVER['REQUEST_METHOD']){
        case 'POST':
        save();
        break;
        case 'GET':
        fetch();
        break;
        case 'PUT':
        save();
        break;
        case 'DELETE':
                    // delete item
        destroy();
        break;
    }


    function fetch() {
        $pdo=new PDO("mysql:dbname=nomade;host=localhost","","");
        $sql = "SELECT * FROM users";
        if (isset($_GET['id'])) $sql .= " WHERE id =".$_GET['id'];
        $statement=$pdo->prepare($sql);
        $statement->execute();
        $results=$statement->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode($results);
    }


    function save() {
        $pdo=new PDO("mysql:dbname=nomade;host=localhost","","");
        $data = json_decode(file_get_contents('php://input'));
        $nom = $data->{'nom'};
        $prenom = $data->{'prenom'};
        $age = $data->{'age'};
        $statement=$pdo->prepare("INSERT INTO users (prenom, nom, age) VALUES ('".$nom."','".$prenom."',$age)");
        $statement->execute();
        $results=$statement->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode($results);
    }
?>

修改 当我做一个

var user = new User({id: options.id});
        user.fetch({
            success: function(user){
                console.log(user.attributes[0]);
                // var template = _.template($('#edit-user-template').html(), {});
                // that.$el.html(template);
            }
        });

我明白了:

 Object {id: "5", nom: "dsfsdfqds", prenom: "qsdfqsdf", age: "12"}

为什么?

1 个答案:

答案 0 :(得分:2)

我终于做到了。

如果你做了

$results=$statement->fetchAll(PDO::FETCH_ASSOC); 

您将获得一个包含所需内容的对象的模型属性。你可以这样解析它:

以下是我的观点:

var EditUser = Backbone.View.extend({
    el: ".page",
    render: function(options) {
        var that = this
        if (options.id) {
            var user = new User({id: options.id});
            user.fetch({
                success: function(user){
                    var template = _.template($('#edit-user-template').html(), {user: user.attributes['0']});
                    that.$el.html(template);
                }
            });
        } else {
            var template = _.template($('#edit-user-template').html(), {user:null});
            this.$el.html(template);
        }

    },
    events: {
        'submit .edit-user-form' : 'saveUser',
    },

    saveUser: function(ev){
        data = $(ev.currentTarget).serializeObject();
        var user = new User();
        user.save(data, {
            success: function(user) {
                router.navigate('', {trigger:true})
            }
        });
        return false;
    }
});

与模板相关:

<script type="text/template" id="edit-user-template">
<form  class="edit-user-form">
<legend><%= user ? "Créer" : "Mettre à jour" %> un user</legend>
<label>Prenom</label>
<input type="text" name="prenom" value="<%= user ? user['prenom'] : '' %>" placeholder="">

<label>Nom</label>
<input type="text" name="nom" value="<%= user ? user['nom'] : '' %>" placeholder="">

<label>Age</label>
<input type="text" name="age" value="<%= user ? user['age'] : '' %>" placeholder="">

<hr>
<input type="submit" name="submit" value="Envoyer" placeholder="" class="btn">

</form>
</script>

但是如果你做了

$results=$statement->fetchObject();

它将返回用户。谢谢@WiredPrairie,我太傻了,改变了我的«save»功能而不是«fetch»功能。