如何使用 Backbone.js 捕获表单提交

And*_*ios 1 javascript backbone.js backbone-events

apply当我在输入字段中输入数据后测试并单击按钮时,出现文件未找到错误

Login按钮是一个虚拟按钮,没有任何功能。我只想显示一个警告框,上面写着“您已成功登录(此处的用户名)!!!” 单击“应用”后。

var Credentials = Backbone.Model.extend({});

var LoginView = Backbone.View.extend({
  el: $("#login-form"),

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

  initialize: function(){
    var self = this;

    this.firstname = $("#username");
    this.lastname = $("#lastname");
    this.number = $("#number");
    this.username = $("#username");
    this.password = $("#password");

    this.firstname.change(function(e){
      self.model.set({firstname: $(e.currentTarget).val()});
    });

    this.lastname.change(function(e){
      self.model.set({lastname: $(e.currentTarget).val()});
    });

    this.number.change(function(e){
      self.model.set({number: $(e.currentTarget).val()});
    });

    this.username.change(function(e){
      self.model.set({username: $(e.currentTarget).val()});
    });

    this.password.change(function(e){
      self.model.set({password: $(e.currentTarget).val()});
    });
  },

  login: function(){
    var firstn= this.model.get('firstname');
    var lastn= this.model.get('lastname');
    var numb= this.model.get('number');
    var user= this.model.get('username');
    var pword = this.model.get('password');

    alert("You logged in as " + user + "Succesfully!!!");

    return false;
  }
});

window.LoginView = new LoginView({model: new Credentials()});
});
Run Code Online (Sandbox Code Playgroud)
<form action="/login" id="login-form" align="left">
    <h1> Your Registration Form:</h1>

    First Name <input type="text" id="firstname" placeholder="First Name">
    Last Name <input type="text" id="lastname" placeholder="Last Name">
    Phone No. <input type="text" id="number" placeholder="1(555)555-5555">
    UserName <input type="text" id="username" placeholder="UserName">
    Password <input type="password" id="password" placeholder="Password">

    <button id="login" onclick="">Apply</button>
    <!-- dummy button  -->
    <button id="login-button">Login</button>
</form>
Run Code Online (Sandbox Code Playgroud)

Emi*_*ron 6

为什么会出现找不到文件的错误?

您会收到文件未找到错误,因为表单已提交,并且操作的"/login"默认方法是GET请求,因此提交会GETlogin页面发出请求,但该页面在服务器上不存在。服务器返回File not found错误。

如何防止提交?

您需要使用 JavaScript 停止提交。为此,首先捕获提交事件,然后调用.preventDefault()提交事件对象。

如何用Backbone捕获提交事件?

Backbone 提供events景观

事件哈希(或方法)可用于指定一组 DOM 事件,这些事件将通过delegateEvents.

以下是捕获submit事件的最简单方法,假设视图的根元素是表单,就像在代码中一样。

events: {
    "submit": "onSubmit",
},

onSubmit: function(e) {
    // `e` being a standard DOM event
    e.preventDefault();
}
Run Code Online (Sandbox Code Playgroud)

这里我简化了你的观点:

var LoginView = Backbone.View.extend({
    // Put the string into a template to ease the manipulation later on.
    template: _.template("You logged in as <%= username %> and a password of <%= password %>\nFirstName:<%= firstname %>\nLastName:<%= lastname %>\nNumber:<%= number %>"),
    el: $("#login-form"),

    events: {
        // listen for the submit event of the form
        "submit": "onSubmit",
        // listen to events from here
        "change #username": 'onUsernameChange'
    },

    initialize: function() {
        // it's a good idea to cache jQuery objects like this.
        this.firstname = $("#username");
        this.lastname = $("#lastname");
        this.number = $("#number");
        this.username = $("#username");
        this.password = $("#password");

        // but avoid extensive `change` listeners as it's inefficient and
        // useless in this case. If you want to listen to changes, do it 
        // in the events hash, like the "onUsernameChange" example.
    },

    onSubmit: function(e) {
        // prevent the submit and do what you want instead
        e.preventDefault();

        // Set directly with an object, it's quick and clean.
        this.model.set({
            firstname: this.firstname.val(),
            lastname: this.lastname.val(),
            number: this.number.val(),
            username: this.username.val(),
            password: this.password.val()
        });

        // use the template for the alert.
        alert(this.template(this.model.toJSON()));
    },

    onUsernameChange: function(e) {
        // no need for jQuery for a trivial value retrieval
        console.log(e.currentTarget.value);
    }
});
Run Code Online (Sandbox Code Playgroud)

指定默认的表单按钮类型属性submit。因此,创建#login-buttonatype="button"确保它不会触发提交。

<button type="submit" id="login">Apply</button>

<!-- dummy button  -->
<button type="button" id="login-button">Login</button>
Run Code Online (Sandbox Code Playgroud)

为什么使用上面的确切代码时它不起作用?

请注意,视图的根元素是使用el属性指定的。

在您的初始代码中,您使用jQuery 的核心函数来查找表单元素并将其传递给视图。但为了让它工作,表单元素必须在运行视图的 JS 之前存在。

所以 HTML 页面结构应该是这样的:

<html>
    <head>
        <!-- head stuff like CSS, title, etc.  -->
    </head>
    <body>
        <form id="login-form">
            <!-- rest of the form goes here -->
        </form>

        <!-- Load the scripts here -->
        <script src="libs/jquery/dist/jquery.js"></script>
        <script src="libs/underscore/underscore.js"></script>
        <script src="libs/backbone/backbone.js"></script>

        <!-- then your own code can go here, or into another js file. -->
        <script>
            // your view, etc.
        </script>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)