我希望你能帮助我。我正在尝试使用 mysql 和主干从我的数据库中获取数据。问题是我可以创建一个“用户”,并且我可以获取所有这些用户。但是当我尝试制作时:
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"}
为什么 ?