基于w3schools教程(https://www.w3schools.com/html/tryit.asp?filename=tryhtml_form_submit),以下表单将以以下格式提交其输入内容:firstname = Mickey&lastname = Mouse。有没有办法使用javascript或JQuery提取这种格式的输入?谢谢!
<form action="/action_page.php">
First name:<br>
<input type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br><br>
<input type="submit" value="Submit">
</form>
答案 0 :(得分:0)
您可以使用jQuery来获取它:
$('form').serializeArray();
答案 1 :(得分:0)
为了将输入字段值发送到URL,必须使用JavaScript将所有字段值收集到FormData或Array中。然后,您可以将该变量发送到URL的下一页
检查:
function getFieldArray()
{
console.log('Example : 1 Get all fields in FormData Array');
var formData = new FormData();
var elements = document.getElementById("myForm1").elements;
for (var i = 0, element; element = elements[i++];) {
if (element.type === "text")
{
console.log('This is textbox id = ' + element.id + ', Value = ' + element.value);
formData.append(element.id, element.value);
}
}
//Example : 1 END
console.log('\n-----------------------------\n\n');
console.log('Example : 2 Get all fields in Array');
var fieldsArr = [];
var frmElements = document.getElementById("myForm1").elements;
for (var i = 0, element; element = frmElements[i++];) {
if (element.type === "text")
{
fieldsArr[i] = element.value;
}
}
console.log('Fields Length : ' + fieldsArr.length);
return false;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm1">
First name:<br>
<input id="firstname" type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input id="lastname" type="text" name="lastname" value="Mouse">
<br><br>
<button onclick="return getFieldArray()">Submit</button>
</form>
您可以将FormData发送到另一页。
$.ajax({
type: "POST",
url: 'new_page.html',
data: formData,
processData: false,
contentType: false,
dataType: 'html',
success: function (response) {
//alert('done')
},
error: function (error) {
//alert('fail');
}
});
答案 2 :(得分:0)
serializeArray()函数将为您提供您在表单中提交的所有数据,只需在表单上调用该函数即可。