简体   繁体   English

如何在Javascript中访问用户提交的表单数据?

[英]How do I access form data submitted by a user in Javascript?

I'm relatively new to programming, but understand the basics of HTML, CSS, and Javascript (including jQuery). 我对编程比较陌生,但是要理解HTML,CSS和Javascript(包括jQuery)的基础知识。 Due to my greenness, I'd appreciate it if answers contained both a simple solution and a reason as to why the solution works. 由于我的绿色,如果答案都包含一个简单的解决方案和理由, 为什么解决方案的工作我会感激。 Thanks! 谢谢!

So I've got a form, with a text input and a submit button: 所以我有一个表单,带有文本输入和提交按钮:

<form>
<input type="text">
<button type="submit">Submit</button>
</form>

When the user types data into the text field and clicks submit, how do I gain access to this data? 当用户在文本字段中键入数据并单击提交时,如何获取对此数据的访问权限? If a user inputs their name, how do I grab that information? 如果用户输入了他们的名字,我该如何获取该信息? I don't intend to store it or write it anywhere, just to hold onto it as a variable in javascript, which I'll assign to a jQuery cookie. 我不打算将它存储或写在任何地方,只是为了将其作为javascript中的变量保留,我将其分配给jQuery cookie。

So how do I access the data that the user has submitted, preferably using only Javascript (with jQuery)? 那么如何访问用户提交的数据,最好只使用Javascript(使用jQuery)? Thanks for the help! 谢谢您的帮助!

You access the data on the server side (in PHP via $_POST['username'] for example). 您可以访问服务器端的数据(例如,通过$_POST['username']在PHP中)。 The form sends data to your sever for any named input, so you would probably have to change the input to: 表单将数据发送到您的服务器以获取任何命名输入,因此您可能必须将输入更改为:

<input type=text name=username>

If you want to access it on the client side (with JavaScript), you can do that too, but you have to prevent the form from submitting: 如果您想在客户端(使用JavaScript)访问它,您也可以这样做,但您必须阻止表单提交:

$("form").on('submit', function (e) {
    $.cookie('username', $(this).find('[name=username]').val());
    //stop form from submitting
    e.preventDefault();
});

say you had an html input tag such as: 说你有一个html输入标签,例如:

<input id="textfield" type="text">

using javascript, you can store the value of that field in a variable like this: 使用javascript,您可以将该字段的值存储在变量中,如下所示:

var inputvalue = $('#textfield').val();

of course, you'll need something to run the script. 当然,你需要一些东西来运行脚本。

the reason this works is that the the textfield is an object. 这有效的原因是文本字段是一个对象。 you might think of it as a tree trunk with different branches coming out. 你可能会认为它是一个树干,有不同的树枝出来。 one of these "branches" is the value contained inside of it. 其中一个“分支”是其中包含的值。 since you know jquery, you know that $('#textfield') gets the element by a selector. 因为你知道jquery,你知道$('#textfield')通过选择器获取元素。 the period says we're getting one of the branches, and "value" says we want the branch that tells what's in the textfield. 期间说我们得到了一个分支,“价值”说我们想要分支来告诉文本字段中的内容。

hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM