javascript - 为什么我的 form.action 与表单提交的不同?

标签 javascript php html get forms

我正在尝试设置一个表单,通过用户填写的表单将数据传输到我的 php 文件。我想创建自己的 GET 请求以简化它,但是当我提交表单时,它的 URL 与我创建的不同。

我控制台记录了我的 form.action 并得到了(都是伪造的数据):

.../index.php?search1=987654321&search2=987654321

但我得到的 URL 是(我输入了 987654321):

/index.php?search1=987654321

文件:index.html

<form id="searchForm" action="/index.php" method="GET">
    <input type="submit" value="Search" onclick="createActionGetRequest()">
    <br><br>
    <text id="search1Text">Social Security Number</text><input id="searchField1" type="text" name="search1"><br>
    <text id="search2Text"></text>
</form>

文件:helper-functions.js

function createActionGetRequest()
{
  var form = document.getElementById("searchForm");
  var elements = form.elements;
  var values = [];

  for (var i = 0; i < elements.length; i++)
  {
    values.push(encodeURIComponent(elements[i].name) + '=' + encodeURIComponent(elements[i].value));
  }

  var userForm = document.getElementById("userType");
  values.push(encodeURIComponent("userType") + '=' + encodeURIComponent(userForm.value));

  var searchForm = document.getElementById("searchType");
  values.push(encodeURIComponent("searchType") + '=' + encodeURIComponent(searchForm.value));

  // dummy test for GET request
  form.action += '?' + "search1=987654321" + '&' + "search2=987654321";
  console.log(form.action);
  alert('pause');
  form.submit();
}

最佳答案

当您点击表单中的提交按钮时,浏览器总是调用 form.submit()。这意味着进行了 2 次调用,/index.php?search1=987654321 由浏览器调用,/index.php?search1=987654321&search2=987654321 由您的 js 代码调用

您可以将 event.preventDefault() 添加到 createActionGetRequest() 以阻止浏览器调用。

function createActionGetRequest(event)
{
   event.preventDefault()
   ...
}

GET 方法还将请求查询替换为表单输入值。您可以添加另一个输入而不是更改 form.action。

var input = document.createElement("input"); 
input.type = "text"; 
input.name = "search2"; 
form.appendChild(input); 

关于javascript - 为什么我的 form.action 与表单提交的不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55913771/

相关文章:

javascript - oboe.js - 选择特定 Node 而不是所有匹配的模式?

html - 将验证码控件包装在 p 标签中,如何将其向右移动?

php - 日期比较仅考虑时间 (PHP)

html - 将 url 图片大小调整为相等的部分

html - Bootstrap : responsive div in between two fixed div elements

javascript - Node.Js 中的异步问题 - 如何执行一系列操作?

javascript - 重新定义的 toString 的 getOwnPropertyDescriptor 应该是未定义的

javascript - "Failed to execute 'appendChild' on 'Node'”是什么意思?

javascript - 如果使用 XMLHttpRequest 发送 wav 文件,如何在 PHP 中将其保存在服务器上?

php - 我可以将表单操作发送到公共(public)文件夹外的 php 文件吗?