我有一个带有一些默认值和一个 url 的 backbone.js 模型:
var Box = Backbone.Model.extend({
url: "./save.php",
defaults: {
x: 0,
y: 0,
w: 1,
h: 1
}
});
然后我有一个这个模型的实例,我继续保存它:
var box = new Box({ x:10, y:10, w:200, h:200 });
box.save();
现在我想使用 PHP 脚本“save.php”将这个模型保存到 MySQL 数据库中,它是这样的:
<?php
include('connection.php');
$id = $_POST['cid'];
$x = $_POST['x'];
$y = $_POST['y'];
$w = $_POST['w'];
$h = $_POST['h'];
mysql_query("INSERT INTO boxes (id, x, y, w, h)
VALUES('$id', '$x', '$y', '$w', '$h')
") or die(mysql_error());
?>
echo "Data Inserted!";
我已尝试阅读许多教程,但无法保存这个简单的模型。为什么我的代码不起作用?关于如何解决这个问题的任何想法?
谢谢
编辑:快速解决方案
在php脚本中,从发送的JSON对象中获取信息的正确方式如下:
$box_data = json_decode(file_get_contents('php://input'));
$x = $box_data->{'x'};
$y = $box_data->{'y'};
$w = $box_data->{'w'};
$h = $box_data->{'h'};
并存储在数据库中:
mysql_query("INSERT INTO boxes(id, x, y, w, h)
VALUES('', '$x', '$y', '$w', '$h') ")
or die(mysql_error());
以这种方式,将在表“boxes”中插入一行,其中包含 Backbone 模型 Box 的每个属性的信息。 本例中服务器请求方式为POST,表“boxes”中的id设置为自增。
最佳答案
Backbone 基于 REST API:当将模型保存/更新到服务器时,Backbone 将在请求正文中将其序列化为 JSON 并使用 POST
我们的 PUT
要求。来自 Backbone.sync documentation
With the default implementation, when Backbone.sync sends up a request to save a model, its attributes will be passed, serialized as JSON, and sent in the HTTP body with content-type application/json.
这意味着你必须在服务器端
- 确定请求的类型
- 解码序列化的JSON
像这样的事情应该让你开始
$request_method = strtolower($_SERVER['REQUEST_METHOD']);
$data = null;
switch ($request_method) {
case 'post':
case 'put':
$data = json_decode(file_get_contents('php://input'));
break;
}
// print_r($data);
// note that mysql_* functions are deprecated
// http://php.net/manual/en/function.mysql-query.php
// inserting with a PDO object, assuming an auto incremented id
$sql = "INSERT INTO boxes (x, y, w, h) VALUES(?, ?, ?, ?)";
$sth = $dbh->prepare($sql);
$sth->execute(array(
$data->x,
$data->y,
$data->w,
$data->h
));
$id = $dbh->lastInsertId();
查看此页面以在 PHP 中更彻底地实现 REST API http://www.gen-x-design.com/archives/create-a-rest-api-with-php/
关于php - 将 Backbone.js 模型插入 MySQL 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10930789/