javascript 如何将输入字段值作为将在单击提交按钮时打开的 url 查询字符串传递?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30241407/
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-28 11:56:20  来源:igfitidea点击:

How to pass input field values as a url query string that will be opened on click of a submit button?

javascriptforms

提问by nolawi

I would have to input fields like this

我将不得不输入这样的字段

 <form>
    <input type="text" id="keyword" placeholder="XXX">
    <input type="text" id="state" placeholder="XXX">
    <button type="submit" id="submit">Submit</button>
 </form>

On click of the submit I would like to send them to a new page with the value of the input appended to the url with query string.

单击提交时,我想将它们发送到一个新页面,并将输入值附加到带有查询字符串的 url。

 http://www.link.com/page?keyword=XYXYX&state=XZXX

Here is my start thinking but was thinking .serialize()can handle this better than this example

这是我的开始思考,但我认为.serialize()可以比这个例子更好地处理这个问题

  var keywordVal = $("#keyword").val();
  var stateVal = $("#state").val();

  $( "form" ).on( "submit", function() {
   event.preventDefault();
   location.href='http://www.link.com/page?keyword=' + keywordVal + '&state=' + stateVal
  });

let me know if i am approaching it the right way..

让我知道我是否以正确的方式接近它..

回答by Kevin Boucher

You don't need JavaScript to do this.

您不需要 JavaScript 来执行此操作。

Simply add an actionattribute with the URL and set the methodattribute to GET(this will append the named field values as a query string).

只需添加一个action带有 URL 的method属性并将该属性设置为GET(这会将命名字段值附加为查询字符串)。

<form action="<yourURL>" method="GET">
    <input type="text" id="keyword" name="keyword" placeholder="XXX">
    <input type="text" id="state" name="state" placeholder="XXX">
    <button type="submit" id="submit">Submit</button>
</form>

NOTE: You'll need nameattributes on your fields.

注意:您name的字段需要属性。

Fiddle: http://jsfiddle.net/pjh7wkj4/

小提琴:http: //jsfiddle.net/pjh7wkj4/

回答by Manjunatha Thippeswamy

No need any jQuery/javascript to do that, form tag is providing those functionality. Adding action and method (GET) attributes will give you the results what you expect.

不需要任何 jQuery/javascript 来做到这一点,表单标签提供了这些功能。添加操作和方法 (GET) 属性将为您提供预期的结果。

<form action="<target_url>" method="GET">
    <input type="text" id="keyword" name="keyword" placeholder="XXX">
    <input type="text" id="state" name="state" placeholder="XXX">
    <button type="submit" id="submit">Submit</button>
 </form>