【问题标题】:First button in my html doesnt request post, but the other buttons work fine我的 html 中的第一个按钮不请求发布,但其他按钮工作正常
【发布时间】:2018-09-10 08:10:58
【问题描述】:

This is the webpage i have been working on..

这里我有多个从 ejs for 循环中获得的按钮(编辑按钮、删除按钮)。删除工作正常。但是当我单击编辑时,第一个编辑按钮不会发送发布请求,但其他按钮会发送。我无法理解为什么...... 以下是服务器端代码,

  app.post('/todo/edit/:todoId',function(req,res){
    //console.log(req.params.todoId);
    //res.json({url:'todo-edit'});
    res.render('todo-edit',{cat:req.params.todoId});
    console.log('dog');
  });
          <form>
            <% for(var i=0;i<todos.length;i++){ %>
              <% if(todos[i].done){ %>
                <li id="strike"><%= todos[i].item %></li><form action="/todo/edit/<%= todos[i]._id %>" method="post"><button type="submit" class="btn1 <%= todos[i]._id %>">-</button><button id=<%= todos[i]._id %> class="btn2">X</button></form>
              <% }else{ %>
                <li id="nonStrike"><%= todos[i].item %></li><form action="/todo/edit/<%= todos[i]._id %>" method="post"><button type="submit" class="btn1 <%= todos[i]._id %>">-</button><button id=<%= todos[i]._id %> class="btn2">X</button></form>
              <% } %>
            <% } %>
        </form>

【问题讨论】:

  • 您是否收到错误或根本没有任何反应?
  • 什么也没发生
  • todos 数组长什么样子?
  • 但是当点击其他按钮时,它们会将我转发到我想要的位置,只有第一个按钮会出现此问题
  • [ { _id: 5abfa1188665f803c016e334, item: 'Watic movie', done: false, __v: 0 }, { _id: 5abfa1238665f803c016e335, item: 'Go To ell', done: true, __v: 0 } ]

标签: javascript html node.js express ejs


【解决方案1】:

好的,首先,对于这里试图解决这个问题的其他人。这是更可读格式的代码

      <form>
        <% for(var i=0;i<todos.length;i++){ %>
          <% if(todos[i].done){ %>
            <li id="strike"><%= todos[i].item %></li>
            <form action="/todo/edit/<%= todos[i]._id %>" method="post">
                <button type="submit" class="btn1 <%= todos[i]._id %>">-</button>
                <button id=<%= todos[i]._id %> class="btn2">X</button>
            </form>
            <% }else{ %>
                <li id="nonStrike"><%= todos[i].item %></li>
                <form action="/todo/edit/<%= todos[i]._id %>" method="post">
                    <button type="submit" class="btn1 <%= todos[i]._id %>">-</button>
                    <button id=<%= todos[i]._id %> class="btn2">X</button>
                </form>
              <% } %>
            <% } %>
    </form>

其次,

您的列表元素 (li) 未包含在 ul 或 ol 标记中,这是非常糟糕的做法。

最后,由于浏览器技术的限制,您需要查看如何执行“method_override”以创建您的 onw“删除”路由。这样您的操作最终会看起来与此类似。

action="/blogs/?_method=DELETE"

希望这能让你走上正确的道路。

【讨论】:

  • 我按照你说的做了,但它没有解释为什么第一个编辑按钮不起作用而其余的编辑按钮起作用
  • 待办事项数组是什么样的?它只是第一个,当你循环遍历数组时,你从 -1 而不是 0 开始
  • [ { _id: 5abfa1188665f803c016e334, item: 'Watic movie', done: false, __v: 0 }, { _id: 5abfa1238665f803c016e335, item: 'Go To ell', done: true, __v: 0 } ]
  • 我也想过。但是当删除它工作正常。只有编辑按钮会出现问题
  • 编辑按钮对数据库中的第二个项目有效吗?点击编辑按钮后会发生什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-29
  • 1970-01-01
  • 1970-01-01
  • 2012-05-03
  • 2014-07-20
  • 1970-01-01
相关资源
最近更新 更多