Javascript Backbone.js ajax 调用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11331604/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:28:00  来源:igfitidea点击:

backbone.js ajax calls

javascriptbackbone.js

提问by John Cooper

I 'm learning Backbone.js for a new app I'm building. I need to perform an AJAX call(REST SERVICE) to authenticate.

我正在为我正在构建的新应用程序学习 Backbone.js。我需要执行 AJAX 调用(REST SERVICE)来进行身份验证。

Where is the correct place for this call? In the Model, View or somewhere else? specifically related to Backbone.js MVC model.

这个电话的正确位置在哪里?在模型、视图或其他地方?特别与 Backbone.js MVC 模型相关。

<html>
<head>
<script src="lib/jquery-1.6.1.min.js"></script>
<script src="lib/json2.js"></script>
<script src="lib/underscore-min.js"></script>
<script src="lib/backbone-min.js"></script>   

<script language="javascript">
      $(function(){
         var LoginView = Backbone.View.extend({
          el: $("#login-form"),

          events: {
            "click #login": "login"
          },

          login: function(){
              alert("Hello");
           }
        });

        window.LoginView = new LoginView();
      });
    </script>   
  </head>
  <body>
    <form action="/login" id="login-form">
      Username: <input type="text" id="username"><br>
      Password: <input type="password" id="password"><br>
      <button id="login">Login</button>
    </form>
  </body>
</html>

回答by reach4thelasers

Create an authentication Model, that stores the post state (username, password, remember me) as well as the response state (login failed, login accepted)...

创建一个身份验证模型,用于存储发布状态(用户名、密码、记住我)以及响应状态(登录失败、已接受登录)...

App.Model.authentication= Backbone.Model.extend({
    defaults: {
        Username: "",
        Password: "",
        RememberMe: false,
        LoginFailed: false,
        LoginAccepted: false
    },
    url:"api/authentication"
});

Update the View to use the model:

更新视图以使用模型:

   $(function () {
    var LoginView = Backbone.View.extend({
        model: new App.Model.authentication(),
        el: $("#login-form"),
        events: {
            "click #login": "login"
        },

        login: function () {
            this.model.save({username: this.$el.find("#username"),
                password: this.$el.find("#password")}, {
                success: function () {
                    /* update the view now */
                },
                error: function () {
                    /* handle the error code here */
                }
            });
        }
    });
}

);

);

Calling Model.Save() will issue a post request to the server, although in this instance on the server you're not actually saving anything, but check the credentials and sending back an object with the same model, but with the "LoginAccepted" field set appropriately.

调用 Model.Save() 将向服务器发出 post 请求,尽管在这种情况下在服务器上您实际上并未保存任何内容,而是检查凭据并发送回具有相同模型但带有“LoginAccepted”的对象字段设置适当。

Don't implement custom JQuery AJAX Posts - Its not in the spirit of backbone, which handles it all for you under the hood via its REST interface.

不要实现自定义的 JQuery AJAX 帖子——它不符合主干的精神,它通过其 REST 接口在幕后为您处理这一切。

More details on the REST interface and the various REST Actions and URLS that backbone uses here: http://codebyexample.info/2012/04/30/backbone-in-baby-steps-part-3/

有关 REST 接口以及主干在此处使用的各种 REST 操作和 URL 的更多详细信息:http: //codebyexample.info/2012/04/30/backbone-in-baby-steps-part-3/

One more thing on the AJAX vs model.save() debate. If your application was a stateless chat room like IRC - which sends messages to other users in the chat room but doesn't save the messages centrally... would you throw away all of backbone's REST functionality and re-implement them with custom AJAX calls because you're not ACTUALLY 'saving', you're really just 'sending'. That would cost you a huge amount of work to re-implement functionality that's already there, just because of semantics. Always read model.save() as model.post() - its not just for saving - its for sending.

关于 AJAX 与 model.save() 辩论的另一件事。如果您的应用程序是像 IRC 这样的无状态聊天室 - 它向聊天室中的其他用户发送消息但不集中保存消息...您是否会丢弃所有主干的 REST 功能并使用自定义 AJAX 调用重新实现它们因为您实际上并不是在“保存”,而实际上只是在“发送”。仅仅因为语义,这将花费您大量的工作来重新实现已经存在的功能。始终将 model.save() 读作 model.post() - 它不仅用于保存 - 它用于发送。

回答by mvbl fst

You always start in the view because your DOM interactions (incl. form submits) happen in views.

你总是从视图开始,因为你的 DOM 交互(包括表单提交)发生在视图中。

Then, if I were you, I would add a custom method to the User model, and call the method from the view. The login method does not exactly fit with native Backbone sync as you're not trying to add / update / retrieve anything (mind that you DO NOT want to load user password or password hash from the server for security reasons). So you do a regular Ajax call without calling Backbone fetch(). So, here you go:

然后,如果我是你,我会在 User 模型中添加一个自定义方法,并从视图中调用该方法。登录方法并不完全适合本机 Backbone 同步,因为您没有尝试添加/更新/检索任何内容(请注意,出于安全原因,您不想从服务器加载用户密码或密码哈希)。因此,您可以在不调用 Backbone fetch() 的情况下执行常规 Ajax 调用。所以,给你:

var UserModel = Backbone.Model.extend({
  ...
  checkLogin: function(name, password) {
    var self = this;
    $.post('/login', { name: name, password: password }, function(data) {
      self.set(data); // data should be in JSON and contain model of this user
    }, 'json').error(
      self.trigger('loginError'); // our custom event
    );
  }
});

And the view:

和观点:

var UserView = Backbone.View.extend({
  events: {
    'click .login': 'loginSubmit'
  },

  initialize: function() {
     _.bindAll(this, 'loginSubmit', 'loginSuccess', 'loginError');
     this.model.bind('change', this.loginSuccess);
     this.model.bind('loginError', this.loginError);
  },

  loginSubmit: function() {
    var name = 'username', // you get it from some element
        password = '***'; // you get it from another element
    this.model.checkLogin(name, password);
  },

  loginSuccess: function() {
    alert ('You have been logged in');
    console.log(this.model); // should log loaded user model
  },

  loginError: function() {
    alert ('Problem with login');
  }
});

Make sure you pass the UserModel instance to the UserView instance, e.g.:

确保将 UserModel 实例传递给 UserView 实例,例如:

var userModel = new UserModel,
    userView = new UserView({ model: userModel });

回答by srquinn

ReST is NOTa standard, simply a spec and any practical developer will mix ReST and RPC when appropriate to do so. That said, neither of these answers pointed out the fact that the server response should return a token (sessionID, JSON web token, etc.) and delete the plain text password. Failing to do so introduces a security risk.

ReST不是一个标准,只是一个规范,任何实际的开发人员都会在适当的时候混合 ReST 和 RPC。也就是说,这些答案都没有指出服务器响应应该返回令牌(sessionID、JSON Web 令牌等)并删除纯文本密码这一事实。不这样做会带来安全风险。