我有一个带有一些默认值和url的backbone.js模型:
然后我有一个这个模型的实例,我继续保存它:
现在我想使用PHP脚本“save.PHP”将此模型保存到MysqL数据库中,它是这样的:
我试过阅读很多教程,但是我无法将这个简单的模型保存到工作中.为什么我的代码不起作用?关于如何解决这个问题的任何想法?
谢谢
在PHP脚本中,从发送的JSON对象获取信息的正确方法如下:
并存储在数据库中:
以这种方式,将在表“框”中插入一行,其中包含骨干模型框的每个属性的信息.
在这种情况下,服务器请求方法是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,h) VALUES(?,?,?)";
- $sth = $dbh->prepare($sql);
- $sth->execute(array(
- $data->x,$data->y,$data->w,$data->h
- ));
- $id = $dbh->lastInsertId();
查看此页面,以便在PHP http://www.gen-x-design.com/archives/create-a-rest-api-with-php/中更全面地实现REST API