我正在尝试使用 Backbone 和 Yii 框架开发我的第一个 RESTful 应用程序.我对 GET 方法没有任何问题,但我现在坚持使用 POST 方法来创建一个新元素.
I'm trying to do my first RESTful app with Backbone and Yii Framework. I had no problem with the GET methods but I'm stuck now with the POST method, to create a new element.
我在 Backbone 中有一个评论模型:
I have a Comment model in Backbone:
var commentModel = Backbone.Model.extend({
urlRoot: "index.php/api/comments",
idAttribute: 'id',
defaults: {
content: "Empty comment",
status: 1
}
});
在我看来,我添加了一个函数来创建一个新的注释,传递来自相对形式的值:
In my view I add a function to create a new Comment passing the values from the relative form:
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 选项卡中我可以看到所有值:
Looking the request with Firebug it seems all right, in the POST tab I can see all the values:
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 变量是空的!
But in my php Api the $_POST var is empty!
foreach($_POST as $var=>$value) {
if($model->hasAttribute($var))
$model->$var = $value;
else
$this->_sendResponse(500);
}
有人有什么想法吗?阅读 Backbone.Sync 的文档我明白它应该使用 POST 来创建请求.
Anyone has some ideas? Reading the documentation of Backbone.Sync I understand that it should use POST for create request.
我找到了一种从以下位置获取值的解决方法:
I found a workaround getting the values from:
file_get_contents('php://input')
但是我觉得id不合适...
but id doesn't feel right to me...
谢谢.
来自 Backbone.sync 文档,
使用默认实现,当 Backbone.sync 发送请求时保存模型,它的属性将被传递,序列化为 JSON,并在内容类型为 application/json 的 HTTP 正文中发送.
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 响应的正文中接收数据.
which means you won't receive data in parameters like in a regular form post but in the body of the HTTP response.
您有三种选择来处理这种行为:
You've got three options to deal with this behavior:
这篇关于Backbone Sync 返回一个空的 $_POST 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!