使用Backbone.js的POST方法发送数据

时间:2017-01-11 22:24:14

标签: javascript jquery backbone.js codeigniter-3

我使用Backbone.js实现了一个简单的登录系统。

我正在尝试使用HTTP POST方法将用户名和密码传递给处理用户身份验证的Controller类。

public function sessions() {
    if ($this->input->server('REQUEST_METHOD') == 'POST') {
        $this->login();
    } elseif ($this->input->server('REQUEST_METHOD') == 'GET') {
        $this->index();
    } elseif ($this->input->server('REQUEST_METHOD') == 'DELETE') {
        $this->session->sess_destroy();
        $this->index();
    }
}

Backbone.js代码段:

$(document).ready(function() {

    var Session = Backbone.Model.extend({
        url: function() {
            var link = "http://<?php echo gethostname(); ?>/reddit/index.php/welcome/sessions";
            return link;
        },
        defaults: {
            username: null,
            password: null
        }
    });

    var model = new Session();

    var DisplayView = Backbone.View.extend({
        el: ".complete",
        model: model,
        type: 'POST',
        initialize: function() {
            this.listenTo(this.model, "sync change", this.gotdata);
        },
        events: {
            "click #signin": "getdata"
        },
        getdata: function(event) {
            event.preventDefault();
            var username = $("input#username").val();
            var password = $("input#password").val();
            this.model.set({ username: username, password: password });
            this.model.fetch();
        },
        gotdata: function() {
            console.log(this.model.get('username'));
            console.log(this.model.get('password'));
            $("#base-nav").load(location.href + " #base-nav");
            $("#signin-form").load(location.href + " #signin-form");
        }
    });

    var displayView = new DisplayView();
});

我目前使用type属性来定义HTTP方法类型POST。但这似乎不起作用,因为只能使用开发人员控制台观察GET请求。

需要注意的是,当我删除event.preventDefault();时会在单击链接(Preventing full page reload on Backbone pushState)时阻止页面重新加载,但POST请求似乎已成功传递到后端,尽管页面重新加载可防止预期的目标行为。

我们如何使用Backbone.js的POST请求轻松发送数据?

1 个答案:

答案 0 :(得分:5)

您正在使用this.model.fetch();来检索数据。它默认发出GET请求,不会在正文或查询字符串中发送任何数据。

尝试查找选项和功能时,请使用documentationBackbone source code也很简短,易于理解。

快速修复

使用保存

this.model.save();

要强制执行POST请求,就像模型在您已登录时设置了ìd并且只想再次验证登录一样,使用{{ 1}}选项,以便在Backbone确定它是更新而非创建调用时避免typePUT请求。

PATCH

传递给savefetchcreatedestroy的所有选项(均使用Backbone.sync)也会传递给jQuery's ajax功能

现实解决方案

首先,don't generate JS with PHP

然后,在this.model.save(null, { type: 'POST' }); 模型中创建一个函数来处理登录。您甚至可以完全避免使用Backbone REST功能,因为它不适合登录请求的用例。

使用模型很有用,因为它提供了常见的Backbone事件,并且它适用于插件,例如登录表单视图中的双向绑定。但是调用Session登录并不清楚它应该做什么。这就是为什么我们应该为save模型提供明确的API。

Session

然后登录:

var Session = Backbone.Model.extend({
    urlRoot: "http://example.com/reddit/index.php/welcome/sessions",
    defaults: {
        username: null,
        password: null
    },

    // hide the login complexity inside a function
    login: function(options) {
        // for a really simple login, this would be enough
        return this.save(null, { type: 'POST' });

        // for anything more complex, make a custom call.
        return Backbone.ajax(_.extend({
            url: this.url(),
            method: "POST",
            data: this.attributes,
            dataType: "json",
        }, options));
    },

    // provide other functions for a clear and simple to use API.
    logout: function(){ /*...*/ },
    isAuthenticated: function(){ /*...*/ }
});

我个人使用backbone-session插件将身份验证var session = new Session(); // in the view render: function() { // caching jQuery object and uses the view's `$` function to scope // the search to the view element only. this.$username = this.$("input#username"); this.$password = this.$("input#password"); return this; }, getdata: function(){ session.set({ username: this.$username.val(), password: this.$password.val(), }); session.login({ context: this, success: this.onLoginSuccess }); } 保存在token中。它提供了一个很好的API,并使用localStoragesavefetch同步。

为什么要自定义localStorage来电?

Backbone提供ajax根据REST原则将save与服务器同步,这为不需要ID的attributes服务增加了大量开销发出PUT / PATCH请求。

你经常会与Backbone作战。

更多信息