php – 将Backbone.js模型插入MySQL数据库

前端之家收集整理的这篇文章主要介绍了php – 将Backbone.js模型插入MySQL数据库前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个带有一些默认值和url的backbone.js模型:
  1. var Box = Backbone.Model.extend({
  2. url: "./save.PHP",defaults: {
  3. x: 0,y: 0,w: 1,h: 1
  4. }
  5. });

然后我有一个这个模型的实例,我继续保存它:

  1. var Box = new Box({ x:10,y:10,w:200,h:200 });
  2. Box.save();

现在我想使用PHP脚本“save.PHP”将此模型保存到MysqL数据库中,它是这样的:

  1. <?PHP
  2. include('connection.PHP');
  3.  
  4. $id = $_POST['cid'];
  5. $x = $_POST['x'];
  6. $y = $_POST['y'];
  7. $w = $_POST['w'];
  8. $h = $_POST['h'];
  9.  
  10. MysqL_query("INSERT INTO Boxes (id,x,y,w,h)
  11. VALUES('$id','$x','$y','$w','$h')
  12. ") or die(MysqL_error());
  13. ?>
  14. echo "Data Inserted!";

我试过阅读很多教程,但是我无法将这个简单的模型保存到工作中.为什么我的代码不起作用?关于如何解决这个问题的任何想法?

谢谢

编辑:快速解决方

PHP脚本中,从发送的JSON对象获取信息的正确方法如下:

  1. $Box_data = json_decode(file_get_contents('PHP://input'));
  2. $x = $Box_data->{'x'};
  3. $y = $Box_data->{'y'};
  4. $w = $Box_data->{'w'};
  5. $h = $Box_data->{'h'};

并存储在数据库中:

  1. MysqL_query("INSERT INTO Boxes(id,h)
  2. VALUES('','$h') ")
  3. or die(MysqL_error());

以这种方式,将在表“框”中插入一行,其中包含骨干模型框的每个属性的信息.
在这种情况下,服务器请求方法是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

这样的事情应该让你开始

  1. $request_method = strtolower($_SERVER['REQUEST_METHOD']);
  2. $data = null;
  3.  
  4. switch ($request_method) {
  5. case 'post':
  6. case 'put':
  7. $data = json_decode(file_get_contents('PHP://input'));
  8. break;
  9. }
  10.  
  11. // print_r($data);
  12.  
  13. // note that MysqL_* functions are deprecated
  14. // http://PHP.net/manual/en/function.MysqL-query.PHP
  15. // inserting with a PDO object,assuming an auto incremented id
  16. $sql = "INSERT INTO Boxes (x,h) VALUES(?,?,?)";
  17. $sth = $dbh->prepare($sql);
  18. $sth->execute(array(
  19. $data->x,$data->y,$data->w,$data->h
  20. ));
  21. $id = $dbh->lastInsertId();

查看此页面,以便在PHP http://www.gen-x-design.com/archives/create-a-rest-api-with-php/中更全面地实现REST API

猜你在找的PHP相关文章