主干同步返回一个空$ _POST数组 [英] Backbone Sync return an empty $_POST array
问题描述
我试图做我的第一个REST风格的应用程序与骨干网和Yii框架。
我曾与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.
我在骨干评论模型:
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();
},
展望与萤火虫似乎没事的要求,在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发送一个请求
保存模式,其属性将被传递,序列化为JSON,
而在HTTP正文中发送与内容类型的应用程序/ JSON。
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:
- 修改服务器code,了解REST请求,请参阅Insert Backbone.js的模型导入MySQL数据库例如:
- 查看是否 Backbone.emulateJSON 可以回答您的需求
- Backbone.sync 并发送数据,以更好地满足您的服务器
- Modify your server code to understand REST requests, see Insert Backbone.js model into MySQL database for example
- See if Backbone.emulateJSON could answer your needs
- Overwrite Backbone.sync and send the data to better fit your server
这篇关于主干同步返回一个空$ _POST数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!