简体   繁体   English

表单提交时页面重新加载! Rails API 后端 Javascript 前端

[英]Page reload on a form submit! Rails API backend Javascript frontend

I'm having trouble figuring out my javascript.我无法弄清楚我的 javascript。 The e.preventDefault() is not working. e.preventDefault() 不起作用。 I've tried changing the submit input to a button as well.我也尝试将提交输入更改为按钮。 I know with a form and using rails that it has an automatic rage reload but I thought e.preventDefault was suppose to stop that.我知道使用表单并使用 rails 它具有自动愤怒重新加载,但我认为 e.preventDefault 应该阻止它。 Is there some hidden feature in the backend that I need to turn off?后端是否有一些我需要关闭的隐藏功能? I set my project up to be an api by using an api flag.我通过使用 api 标志将我的项目设置为 api。 It also has all the right info for cors.它还包含 cors 的所有正确信息。 My server is showing my data correctly...it's just the frontend I cant get up.我的服务器正在正确显示我的数据……这只是我无法起床的前端。

I'm going to post a sample code I followed.我将发布我遵循的示例代码。


<html lang="en" dir="ltr">

  <head>

    <title>Problems</title>

    <meta charset="utf-8">
    <link rel="stylesheet" href="styles.css">
    <script type="application/javascript" src="src/user.js" charset="UTF-8"></script>
    <script type="application/javascript" src="src/problem.js" charset="UTF-8"></script>

  </head>

  <body>

   <div class="container" id="container">

    <h1>Everyone Has Problems</h1>

        <div id="new-user-and-new-problem-container">
            <form id="new-user-form">
                <label>Your name:</label>
                <input type="text" id="new-user-body"/>
                <input type="submit"/>
            </form>
        </div>

    </div>

    <div id="problems-container" class="problems-container">
    </div>

  </body>

</html>```

src/user.js
```document.addEventListener('DOMContentLoaded', function(){
    User.createUser()
})

class User {

    constructor(user){
        this.id = user.id
        this.name = user.name
        this.problems = user.problems
    }

    static createUser(){
        let newUserForm = document.getElementById('new-user-form')
        newUserForm.addEventListener('submit', function(e){
            e.preventDefault()
            console.log(e);
                fetch('http://localhost:3000/api/v1/users', {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json",
                        "Accept": "application/json"
                    },
                    body: JSON.stringify(
                        {
                            user: {
                                name: e.target.children[1].value
                            }
                        })
                    })
                        .then(resp =>  {
                            return resp.json()
                        })
                        .then(user => {
                            let newUser = new User(user)
                            newUser.displayUser()
                        })
        })
    }

    displayUser() {
        let body = document.getElementById('container')
        body.innerHTML = ''
        let userGreeting = document.createElement('p')
        userGreeting.setAttribute('data-id', this.id)
        let id = userGreeting.dataset.id
        userGreeting.innerHTML = `<h1>Hey, ${this.name}!</h1>`
        body.append(userGreeting)
        if (this.problems) {
            this.problems.forEach(function(problem){
                let newProblem = new Problem(problem)
                newProblem.appendProblem()
            })
        }
        Problem.newProblemForm(this.id)
    }

}```

src/problem.js
```class Problem {

    constructor(problem){
        this.id = problem.id
        this.name = problem.name
        this.description = problem.description
    }

    static newProblemForm(user_id) {
        let body = document.getElementById('container')
        let form = 
            `
                <form id="new-problem-form">
                    <label>What's your problem?:</label>
                    <input type="text" id="problem-name"/>
                    <label>Describe it:</label>
                    <input type="text" id="problem-description"/>
                    <input type="submit"/>
                    <h4>Your current problems:</h4>
                </form>
            `
        body.insertAdjacentHTML('beforeend', form)
        Problem.postProblem(user_id)
    }

    //is it appropriate for this to be a static method?
    static postProblem(user_id) {
        let newForm = document.getElementById('new-problem-form')
        newForm.addEventListener('submit', function(e){
            e.preventDefault()
            fetch('http://localhost:3000/api/v1/problems', {
                method: "POST",
                headers:{
                    "Content-Type": "application/json",
                    "Accept": "application/json"
                },
                body: JSON.stringify(
                    {
                        problem: {
                            name: e.target.children[1].value,
                            description: e.target.children[3].value,
                            user_id: user_id
                        }
                    }
                )
            })
            .then(resp => resp.json())
            .then(json => {
                let newProblem = new Problem(json)
                newForm.reset()
                newProblem.appendProblem()

            })
        })
    }

    appendProblem(){
        let problems = document.getElementsByClassName('problems-container')
        let li = document.createElement('li')
        li.setAttribute('data-id', this.id)
        li.setAttribute('style', "list-style-type:none")
        li.innerHTML = `${this.name} ~~ ${this.description}`
        let solveForm = `<button type="button" id="${this.id}" class="solve-problem"> Solve </button>`
        li.insertAdjacentHTML('beforeend', solveForm)
        problems[0].append(li)
        let button = document.getElementById(`${this.id}`)
        this.solve(button)
    }

    solve(button){
        button.addEventListener('click', function(e){
            e.preventDefault()
            fetch(`http://localhost:3000/api/v1/problems/${e.target.parentNode.dataset.id}`, {
                    method: "DELETE"
            })
                    e.target.parentElement.remove();
        })
    }

}```

Try not splitting the element up.尽量不要拆分元素。

document.getElementById('new-problem-form').
  addEventListener('submit', function(e){
   e.preventDefault()
  }

even Jquery偶Jquery

$('#new-problem-form').addEventListener('submit', function(e){
   e.preventDefault()
});

The preventDefault is working on the event.. Take this for example: preventDefault 正在处理该事件。例如:

 $('#message').keydown(function (e) {
      if (e.keyCode == 13) {
          e.preventDefault();
          return false;
      }
  });

This is preventing the enter key from defaulting the submit based on the keydown function.这可以防止 enter 键基于 keydown function 默认提交。 Is this option the actual 'default' you're trying to stop?这个选项是你试图停止的实际“默认”吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM