javascript - 防止在单击按钮时提交表单时重新加载页面

标签 javascript jquery post servlets forms

我有一个 HTML 表单,我在单击“保存”按钮时提交该表单,但页面会重新加载。

我已将 type=button 设置为保存按钮,但仍然发生

我的代码的功能

  • 我有一个表单,里面有 HTML 表格
  • 我正在为我想要后端的每个文件设置属性name=quantity
  • 我在 servlet Post 方法中使用 request.getParameter 方法来获取这些值

工作代码片段

var tableDataDraft = [{
    "Item Code": "1388",
    "Item Name": "Bakala Bhath",
    "Selling Price": "60.0000",
    "Quantity": "1478.0000"
  },
  {
    "Item Code": "1389",
    "Item Name": "Bisibelebath",
    "Selling Price": "68.0000",
    "Quantity": "2596.0000"
  },
  {
    "Item Code": "1409",
    "Item Name": "Puliogare",
    "Selling Price": "60.0000",
    "Quantity": "3698.0000"
  }
]
var itemsQuantiry1 = [];

function addTableDraft(tableDataDraft) {
  var col = Object.keys(tableDataDraft[0]);
  var countNum = col.filter(i => !isNaN(i)).length;
  var num = col.splice(0, countNum);
  col = col.concat(num);
  var table = document.createElement("table");
  var tr = table.insertRow(-1); // TABLE ROW.
  for (var i = 0; i < col.length; i++) {
    var th = document.createElement("th"); // TABLE HEADER.
    th.innerHTML = col[i];
    tr.appendChild(th);
    tr.classList.add("text-center");
    tr.classList.add("head")
  }
  for (var i = 0; i < tableDataDraft.length; i++) {
    tr = table.insertRow(-1);
    tr.classList.add("item-row");
    for (var j = 0; j < col.length; j++) {
      let tabCell = tr.insertCell(-1);
      var hiddenField = document.createElement("input");
      hiddenField.style.display = "none";
      var tabledata = tableDataDraft[i][col[j]];
      if (tableDataDraft[i]['Item Code'] === tableDataDraft[i][col[j]]) {
        tabCell.innerHTML = tabledata;
        hiddenField.setAttribute('name', 'Item_Code');
        hiddenField.setAttribute('value', tabledata);
        tabCell.appendChild(hiddenField);
      }
      if (tableDataDraft[i]['Item Name'] === tableDataDraft[i][col[j]]) {
        tabCell.innerHTML = tabledata;
        hiddenField.setAttribute('name', 'Item_Name');
        hiddenField.setAttribute('value', tabledata);
        tabCell.appendChild(hiddenField);
      }
      if (tableDataDraft[i]['Selling Price'] === tableDataDraft[i][col[j]]) {
        tabCell.innerHTML = tabledata;
        hiddenField.setAttribute('name', 'Selling_price');
        hiddenField.setAttribute('value', tabledata);
        tabCell.appendChild(hiddenField);
      }
      if (tableDataDraft[i]['Outlet Id'] === tableDataDraft[i][col[j]]) {
        tabCell.innerHTML = tabledata;
        hiddenField.setAttribute('name', 'Outlet_Id');
        hiddenField.setAttribute('value', tabledata);
        tabCell.appendChild(hiddenField);
      }
      if (tableDataDraft[i]['Quantity'] === tableDataDraft[i][col[j]]) {
        var quantityField = document.createElement("input");
        quantityField.style.border = "none";
        quantityField.style["text-align"] = "right";
        quantityField.setAttribute("name", "Quantity");
        quantityField.setAttribute("autocomplete", "on");
        if (itemsQuantiry1[i]) {
          quantityField.setAttribute("value", itemsQuantiry1[i]);
        } else {
          quantityField.setAttribute("value", tabledata);
        }
        quantityField.setAttribute("index", i);
        quantityField.setAttribute("type", "number");
        quantityField.setAttribute("onfocus", "this.value=''");
        quantityField.setAttribute("required", "required");
        quantityField.classList.add("dataReset");
        quantityField.toLocaleString('en-IN');
        tabCell.appendChild(quantityField);
      }

      if (j > 1)
        tabCell.classList.add("text-right");
    }
  }
  var divContainer = document.getElementById("HourlysalesSummary");
  divContainer.innerHTML = "";
  divContainer.appendChild(table);
  table.classList.add("table");
  table.classList.add("table-striped");
  table.classList.add("table-bordered");
  table.classList.add("table-hover");

  $(".dataReset").focus(function() {
    $("#loadDraft").hide();
    $("#saveDraft").show();
  });
  $(".dataReset").on("change", function(e) {
    itemsQuantiry1[$(this).attr('index')] = e.target.value;
  });
}

addTableDraft(tableDataDraft);
var btnSave = document.getElementById("save");
var form = document.getElementById("indentForm");

btnSave.addEventListener("click", function(elem) {
  //setting form action here for save 
  form.setAttribute("action", "InsertQuantityIndent");
  form.setAttribute("method", "Post");
  form.submit();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css">
<div class="container" id="divHide">
  <form action="InsertQuantityIndent" method="post" id="indentForm" autocomplete="on">
    <div class="row position-relative">

      <div class="col-lg-4">
        <h5 id="commonHeader">Outlet Code</h5>
        <select class="test" id="outletCode" name="outletCode">
          <option>S0001</option>
          <option>S0002</option>
          <option>S0003</option>
        </select>
      </div>
      <div class="col-lg-4">
        <h5 id="commonHeader">Category</h5>
        <select class="test" id="CategoryName" name="categoryCode">
          <option>C001</option>
          <option>C002</option>
          <option>C003</option>
        </select>
      </div>
    </div>
    <hr style="border: 1px solid black">
    <div>
      <button type="button" id="save" class="commonButton">
					<i class="fas fa-save"></i>Save
				</button>



    </div>
    <div class="table-responsive">
      <table class="w-100" id=HourlysalesSummary></table>
    </div>

  </form>
</div>

当我单击“保存”时,它会转到我的 servlet,并且页面加载为空白。

我知道 $("#indentForm").submit(function(event){event.preventDefault()....}),但我该如何使用它?

然后,当我在帖子中通过 request.getParameter 时,我是否能够在后端获取表单值。

我只是想阻止在我的表单上提交,我不想让它变得复杂,因为我必须使用其他方法将数据发布到我不知道的后端。

This is how my page looks alike when I click save

最佳答案

您应该使用 Ajax 来发送请求,而不是使用默认的 html 表单提交。这是一个例子。

$(document).ready(function(e) {
    
    $("form[ajax=true]").submit(function(e) {
        
        e.preventDefault();
        
        var form_data = $(this).serialize();
        var form_url = $(this).attr("action");
        var form_method = $(this).attr("method").toUpperCase();

        
        $.ajax({
            url: form_url, 
            type: form_method,      
            data: form_data,     
            cache: false,
            success: function(returnhtml){                          
                $("#result").html(returnhtml);                     
            }           
        });    
        
    });
    
});
body{
    font-family: 'Open Sans', 'Helvetica Neue', 'Arial', sans-serif;
    font-size: 13px;       
}

form span{  
    display: block;
    margin: 10px;
}

label{
    display: inline-block;
    width: 100px;     
}

input[type="text"]{
    border: 1px soild #ccc;
    width: 200px;
    padding: 5px;
}

input[type="submit"]{
     padding: 5px 15px;       
}

span#result{
    padding: 5px;
    background: #ff9;        
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" action="/url/of/your/backend/endpoint" ajax="true">
    
    <span id="result">jQuery + AJAX form submit script.</span>
   
    <span>        
        <label>Message: </label>
        <input type="text" name="html" placeholder="Howdy..." />
    </span>
    
    <span>

        <input type="submit" value="Submit" />      
    </span>
    
</form>

关于javascript - 防止在单击按钮时提交表单时重新加载页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54456442/

相关文章:

delphi - 如何在 Indy (Delphi 10.3 Rio) 中修复 'Access violation at address 00660938 in module Project1.exe. Read of address 00000150.'

Python如何获取图像然后POST(通过请求库)

javascript - 如何仅根据标题行应用一些 jquery 内容

javascript - AngularJS ui-calendar——带有事件的模型

javascript - d3js 在每个轴的末尾显示箭头

php - CodeIgniter 和 Javascript/Jquery 库

javascript - 优化JS函数getclassname

javascript - 获取超出最大调用堆栈大小

javascript - 未捕获的类型错误 : Cannot read property 'toArrays' of undefined

iphone - ASIFormDataRequest NSInvalidArgumentException 异常