php - Backbone Sync 返回一个空的 $_POST 数组

标签 php javascript rest backbone.js yii

我正在尝试使用 Backbone 和 Yii Framework 开发我的第一个 RESTful 应用程序。 我对 GET 方法没有问题,但我现在坚持使用 POST 方法来创建一个新元素。

我在 Backbone 中有一个 Comment 模型:

var commentModel = Backbone.Model.extend({

    urlRoot: "index.php/api/comments",
    idAttribute: 'id',

    defaults: {
        content: "Empty comment",
        status: 1
    }
});

在我看来,我添加了一个函数来创建一个新的 Comment,传递来自相关表单的值:

on_submit: function(e) {
            var new_comment = new Comment({author_id: this.$('#author_text').val(), content: this.$('#content_text').val(), post_id: this.$("#post_text").val(), status: this.$("#status_text").val()});

         new_comment.save();
        },

用 Firebug 查看请求似乎没问题,在 POST 选项卡中我可以看到所有值:

JSON            
author_id "7"   
content "Epic fail"
post_id "7" 
status "2"

Source 
{"content":"Epic fail","status":"2","author_id":"7","post_id":"7"}

但是在我的 php Api 中 $_POST var 是空的!

foreach($_POST as $var=>$value) {

     if($model->hasAttribute($var))
        $model->$var = $value;
     else
        $this->_sendResponse(500);
}

有人有什么想法吗?阅读 Backbone.Sync 的文档,我了解到它应该使用 POST 来创建请求。

我找到了一个从以下位置获取值的解决方法:

file_get_contents('php://input') 

但是我觉得 id 不对...

谢谢。

最佳答案

来自 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.

这意味着您不会像常规表单帖子那样在参数中接收数据,而是在 HTTP 响应的正文中接收数据。

你有三种选择来处理这种行为:

  1. 修改您的服务器代码以理解 REST 请求,参见 Insert Backbone.js model into MySQL database例如
  2. 看看是否Backbone.emulateJSON可以满足您的需求
  3. 覆盖Backbone.sync并发送数据以更好地适应您的服务器

关于php - Backbone Sync 返回一个空的 $_POST 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11774448/

相关文章:

javascript - RequireJS Mismatched anonymous define 由 Drupal 引起的错误?

javascript - 为什么 JavaScript 函数声明在 chrome 和 safari 中表现不同?

rest - 如何解决这个 Yii2 RESTful Web 服务 API 路由错误?

java - REST API 可以有多个模型吗?

php - 搜索关键字可能包含特殊字符的搜索查询是什么?

php - Hooks around 添​​加到 Woocommerce 的购物车

php - mb_detect_encoding 不能在 Windows-1250 (CP1250) 上正常工作

javascript - float 操作按钮重叠

c# - 使用 REST API 列出 Dropbox 文件

javascript - 追加后如何对动态表数据进行排序