javascript 如何在提交表单时排除某些表单字段而不禁用该字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4869987/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 15:10:27  来源:igfitidea点击:

How do I exclude certain form fields upon submission of the form without disabling the field

phpjavascriptajax

提问by Daurice

If I have a form with the following 3 fields:

如果我有一个包含以下 3 个字段的表单:

First Name Last Name Date Of Birth

名字 姓氏 出生日期

When the user fills in all 3 fields and submits you will get the URL

当用户填写所有 3 个字段并提交时,您将获得 URL

http: //fakeURL.php?firstName=Fred&lastName=Flintstone&DateOfBirth=2/5/1952

However, if the user only fills in First Name and Date Of Birth you will get

但是,如果用户只填写名字和出生日期,您将得到

http: //fakeURL.php?firstName=Fred&lastName=&DateOfBirth=2/5/1952 (where lastName has no value)

How do I achieve

我如何实现

http: //fakeURL.php?firstName=Fred&DateOfBirth=2/5/1952 (where lastName and value are removed from the URL)

I don't want to disable the input field upon using onsubmit. Is there a better way than disabled the input field?

我不想在使用 onsubmit 时禁用输入字段。有没有比禁用输入字段更好的方法?

Please help...

请帮忙...

回答by simonbor

Just remove the "name" attribute from the input element.

只需从输入元素中删除“名称”属性。

// using jQuery
$('#inputId').removeAttr('name');

// native Javascript
document.getElementById('inputId').removeAttribute('name');

回答by Dan Grossman

You must either:

您必须:

  1. Remove or disable the field from the form before submitting it
  2. Don't submit the form, instead redirect to a URL you construct from the form yourself
  3. Make an AJAX request instead of leaving the page
  1. 在提交之前从表单中删除或禁用该字段
  2. 不要提交表单,而是重定向到您自己从表单构建的 URL
  3. 发出 AJAX 请求而不是离开页面

Aside from those options, you can't submit this form via GET without all the inputs becoming part of the URL. That's part of the HTML and HTTP specifications.

除了这些选项之外,您无法通过 GET 提交此表单,除非所有输入都成为 URL 的一部分。这是 HTML 和 HTTP 规范的一部分。

回答by Flavius

You should use forms with the GETmethod onlywhen the new page is supposed to be bookmarked and passed around.

只有当新页面应该被加入书签并被传递时,你才应该使用带有该GET方法的表单。

Since you are talking about you taking input from the user(and I presume you also store that input in a database or some similar permanent storage), you should be using POSTinstead.

既然你谈论你从用户输入服用(我想你也存储在数据库中或一些类似的永久存储的是输入),你应该使用POST代替