0

我正在关注教程并尝试将其应用到我的简单登录用例中。

简单的 jQuery ajax 调用是:

$.ajax({
    type: "POST",
    url: "/api/element/User.php",
    data: {
        req: "REQUSERSIGNIN",
        platform: "WEB",
        useremail: $('form#userSignIn #userEmail').val(),
        userpass: $('form#userSignIn #userPassword').val()
    },
    dataType: "json",
    success: function(data) {
        console.log("you've been logged in!"
    }
});

当然这是调用:

$('form#userSignIn').submit();

我使用主干的尝试是:

var events = _.clone(Backbone.Events);

var SigninModel = Backbone.Model.extend({
    url: '/api/element/User.php'
});

    var SignInCollection = Backbone.Collection.extend({
        model: SignInModel
    });

var SigninView = Backbone.View.extend({
    events: {
        'submit form#userSignIn': 'signIn'
    },

    initialize: function() {
        console.log('Sign in view initialized');
    },

    signIn: function(e) {
        e.preventDefault();

        // How do I pass in the data as above?

    }
});

$(document).ready(function(){
    // What do I instantiate to make it all work?
});

我如何传递数据?

4

2 回答 2

0

要启动整个过程,您需要:

var view = new SigninView({
  model: new SignInModel(),
  el: $('#some-element')
}).render();

为了解释更多, $('some-element') 将抓取页面上的一些现有 html,即。

<div id="some-element"></div>

然后调用 render() 将呈现视图并将生成的 html 附加到您的 el(#some-element)

注意,你需要一个渲染方法。因此,在您的视图中创建一个渲染函数:

render: function() {
 var json = this.model.toJSON(); // JSON representation of your model data
 var html = this.template(json); // The html of your sign in view, probably consisting of
                                 // a form and some fields
 this.$el.html(html); // Attach the html to your cached jQuery el

您还需要一个模板属性作为 SignInView 的一部分。为此,您使用 下划线模板。在您的登录视图中:

template: _.template(//some html goes here)

最后,您需要从表单输入中获取数据

// ie. in your template you would have an input like this:
<input id="first-name" type="text" />

然后在你的signInView中,

var firstName = this.$('#first-name').val();
this.model.set('firstName', firstName);
this.model.save() // Calling save will delegate the AJAX call to Backbone            
                  // and send your data back as json
于 2013-09-17T23:52:08.067 回答
0

在你的模型上调用 toJSON()

var data = {
  user: model.toJSON(),
  req: "REQUSERSIGNIN",
  platform: "WEB",
}

然后你可以照常进行

$.ajax({
  type: "POST",
  url: "/api/element/User.php",
  data: data,
  dataType: "json",
  success: function(data) {
    console.log("you've been logged in!"
  }
});
于 2013-09-18T00:20:03.553 回答