【问题标题】:Send data using POST method with Backbone.js使用带有 Backbone.js 的 POST 方法发送数据
【发布时间】:2017-01-11 22:24:13
【问题描述】:

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

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

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 请求轻松发送数据?

【问题讨论】:

  • 您在哪里看到 Backbone 视图中有一个 type 属性?
  • 您似乎将类属性与某些函数选项混淆了。
  • 我在这里看到的。 stackoverflow.com/questions/21771089/…
  • 好吧,你肯定把fetch 选项对象与视图类属性混淆了。没有type 选项可供查看。 typejQuery's ajax函数的一个选项,被Backbone在后台使用。

标签: javascript jquery backbone.js codeigniter-3


【解决方案1】:

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

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

快速修复

使用保存

this.model.save();

要强制执行 POST 请求,例如,如果模型在您已经登录并且只想再次验证登录时设置了 ìd,请使用 type 选项 在 Backbone 确定它是更新而不是创建调用时避免 PUTPATCH 请求。

this.model.save(null, { type: 'POST' });

传递给savefetchcreatedestroy的选项,都使用Backbone.sync,也传递给jQuery's ajax函数。

现实的解决方案

首先,don't generate JS with PHP

然后,在Session 模型中创建一个函数来处理登录。您甚至可以完全避免使用 Backbone REST 功能,因为它并不真正适合登录请求的用例。

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

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(){ /*...*/ }
});

然后登录:

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
    });
}

我个人使用backbone-session插件将auth token保存在localStorage中。它提供了一个很好的开箱即用 API,并使用 savefetchlocalStorage 同步。

为什么要自定义ajax 调用?

Backbone 提供 save 以根据 REST 原则将 attributes 与服务器同步,这为不需要 ID 或发出 PUT/PATCH 请求的 login 服务增加了很多开销.

你经常会与 Backbone 战斗。

更多信息

【讨论】:

  • 如果我们有一个模态框,其中包含我们想要用于身份验证的数据,我不确定为什么快速修复是“快速修复”。对我来说,这将是实际的解决方案。它是 1 行,它是 backbon-ish。如果不需要这样的模型,我们可以直接打jQuery Ajax。也许我遗漏了一些东西,但实现一个不提供任何额外功能的方法似乎有点矫枉过正?
  • @TJ 对于一个简单的一次性登录调用,我可能只是将save 包装在login 函数中。但对于更复杂的事情,我更喜欢自定义 ajax 调用。 Backbone 提供save 以根据REST 原则将属性与服务器同步,这为不需要ID 或制作PUT/PATCH 的登录服务 增加了大量开销。你最终会经常与 Backbone 对抗。使用模型对视图及其 Backbone 事件仍然有用。它还可以很好地与插件配合使用。
猜你喜欢
  • 1970-01-01
  • 2011-10-09
  • 2016-10-24
  • 1970-01-01
  • 2014-07-19
  • 2012-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多