Yii,Backbone save(),数据没有通过$ _POST传递

时间:2014-09-23 09:21:48

标签: php post backbone.js yii sync

这是我在index.php中的JavaScript:

MyModel = Backbone.Model.extend({
        defaults: {
            myID: "",
            myName: ""
        },
        urlRoot: 'testAjaxAdd',
        sync: function(method, model, options) {
            options = options || {};
            options['data'] = {};

            options.data["myID"] = model.get("myID");
            options.data["myName"] = model.get("myName");

            options.data = JSON.stringify(options.data);

            return Backbone.sync.apply(this, arguments);
        }
    });

    MyView = Backbone.View.extend({
        el: '.page',
        render: function(){
            var template = _.template($('#add-owner-template').html(), {});
            this.$el.html(template);
        },
        events: {
            'submit .create-owner-form': 'saveOwner'
        },
        saveOwner: function(events) {
            var myName= $('input#myName').val();

            var owner = new MyModel({
                'myID': "111",
                'myName': myName
            });

            owner.save({},{
                success: function(model, response, options) {

                    console.log('success');
                    console.log(response); // show $_POST from actionSaveOwner in Controller
                    console.log(model.toJSON()); // show model
                    console.log(model.get('myID')); // show owner dbcID
                    console.log(model.get('myName')); // show owner userID
                    console.log(JSON.stringify(options)); // show options
                    console.log(options.data["myID"]); // this is shown undefined in console
                    console.log(options.data["myName"]); // this is shown undefined in console

                },
                error: function(model, response, options) {
                    console.log('error');
                    console.log(response);
                    console.log(model.toJSON());
                }
            });


        }
    });

我已将下面的代码放在我的javascript代码的第一行:

Backbone.emulateHTTP = true;

这是我的表单的html部分,它也是一个javascript模板:

<script type="text/template" id="add-owner-template">
<form class='create-owner-form'>
    <label>Name</label>
    <input type="text" name="myName" id="myName"/>
    <button type="submit" class="btn createcontbutton">Create</button>
</form>
</script>

这是我在Controller中的一个非常简单的操作,用于测试我的主干是否正常工作:

public function actionTestAjaxAdd()
{
    header('Content-type: application/json');

    echo CJSON::encode($_POST);

}

但是,这是我在POST标签中从控制台看到的内容:

Parameters  application/x-www-form-urlencoded   Do not sort
{"myID":"111","myName":"i...

但是,当我在控制台中将其显示回响应时,控制器操作中的$ _POST无效。

1 个答案:

答案 0 :(得分:0)

我终于使用file_get_contents("php://input")解决了这个问题。