Просмотр высокого уровня:
Когда форма отправляется исходным образом, это самая последняя операция, выполняемая браузером, и она выполняется вне области действия движка рендеринга / интерпретатора JavaScript.
Любые попытки перехватить фактический запрос POST или GET через JavaScript невозможны, поскольку этот традиционный веб-запрос происходит исключительно между механизмом браузера и подсистемой сети.
Современное решение:
Для веб-разработчиков становится все более популярным отправлять данные форм с помощью XMLHttpRequest - API веб-браузера, который позволяет интерпретатору JavaScript получать доступ к сетевой подсистеме браузера.
This is commonly referred to as Ajax
Простое, но общепринятое использование этого будет выглядеть примерно так:
<html>
<form id="myForm" onsubmit="processForm()">
<input type="text" name="first_name"/>
<input type="text" name="last_name"/>
<input type="submit" value="Submit">
</form>
<!--Using jQuery and Ajax-->
<script type="text/javascript">
/**
* Function is responsible for gathering the form input data,
* adding additional values to the list, and POSTing it to the
* server via Ajax.
*/
function processForm() {
//Retreive the data from the form:
var data = $('#myForm').serializeArray();
//Add in additional data to the original form data:
data.push(
{name: 'age', value: 25},
{name: 'sex', value: 'M'},
{name: 'weight', value: 200}
);
//Submit the form via Ajax POST request:
$.ajax({
type: 'POST',
url: 'myFormProcessor.php',
data: data,
dataType: 'json'
}).done(function(data) {
//The code below is executed asynchronously,
//meaning that it does not execute until the
//Ajax request has finished, and the response has been loaded.
//This code may, and probably will, load *after* any code that
//that is defined outside of it.
alert("Thanks for the submission!");
console.log("Response Data" +data); //Log the server response to console
});
alert("Does this alert appear first or second?");
}
</script>
</html>
Собственный подход:
До существования XMLHttpRequest одним из решений было бы просто добавить любые дополнительные данные формы непосредственно в документ.
Используя ту же форму, что и выше, метод добавления jQuery может выглядеть следующим образом:
<html>
<form action="myFormProcessor.php" method="POST" id="myForm" onsubmit="return processForm()">
<input type="text" name="first_name"/>
<input type="text" name="last_name"/>
<input type="submit" value="Submit">
</form>
<script type="text/javascript">
/**
* Function is responsible for adding in additional POST values
* by appending <input> nodes directly into the form.
* @return bool - Returns true upon completion to submit the form
*/
function processForm() {
$('<input>').attr('type', 'hidden').attr('name', 'age').attr('value', 25).appendTo('#myForm');
$('<input>').attr('type', 'hidden').attr('name', 'sex').attr('value', 'M').appendTo('#myForm');
$('<input>').attr('type', 'hidden').attr('name', 'weight').attr('value', 200).appendTo('#myForm');
return true; //Submit the form now
//Alternatively you can return false to NOT submit the form.
}
</script>
</html>