【发布时间】:2012-07-31 05:54:53
【问题描述】:
我正在尝试使用 Backbone 和 Yii 框架做我的第一个 RESTful 应用程序。 我对 GET 方法没有任何问题,但我现在坚持使用 POST 方法来创建一个新元素。
我在 Backbone 中有一个评论模型:
var commentModel = Backbone.Model.extend({
urlRoot: "index.php/api/comments",
idAttribute: 'id',
defaults: {
content: "Empty comment",
status: 1
}
});
在我看来,我添加了一个函数来创建一个新的评论,传递来自相关表单的值:
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 变量是空的!
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 不合适...
谢谢。
【问题讨论】:
-
$_SERVER['REQUEST_METHOD']的值是“POST”,所以值应该在 $_POST 数组中,对吗? -
不,方法是POST,但是数据是通过HTTP body发送的。它不会以常规形式发送,将设置参数并将 application/x-www-form-urlencoded 作为 mime 类型。检查此 Fiddle jsfiddle.net/RK7LN 中发送的内容
标签: php javascript rest backbone.js yii