I have a form, and a submit handler in jQuery.
When the user submits the form, I want to modify (add) some parameters to the POST request, before it is despatched from the client to the server.
i.e.
- User clicks 'submit'
- My jQuery submit hander begins execution...
- I create some new key/value pairs and add them to the POST payload
At the moment, it looks like my only options are to use $.post()
, or $('form').append('<input type="hidden" name=... value=...');
Thanks for 开发者_如何学编程any help.
Edit: I've already attached a submit handler to the form; I'm trying to edit the post vars in between the user clicking the submit button, and the request being sent to the server.
Use the submit()
function on the form to create a callback. If the function returns true, the form will be submitted; if false, the form will not post.
$('#theForm').submit(function() {
$("#field1").val(newValue1);
$("#field2").val(newValue2);
$(this).append(newFormField);
return true;
});
etc.
High Level View:
When a form is submitted natively, it is the very last operation a browser performs, and it is executed outside of the scope of the rendering engine/javascript interpreter.
Any attempts of intercepting the actual POST or GET request via JavaScript is impossible as this traditional web request occurs exclusively between the Browser Engine and the Networking Subsystem.
Modern Solution:
It is becoming more popular for web developers to submit form data using XMLHttpRequest -- a web browser API that allows the JavaScript intepreter to access the browser networking subsystem. This is commonly referred to as Ajax
A simple but common use of this would look something like:
/**
* 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 src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<form id="myForm" onsubmit="processForm()">
<input type="text" name="first_name" />
<input type="text" name="last_name" />
<input type="submit" value="Submit">
</form>
Native Approach: Before the existence of XMLHttpRequest, one solution would be to simply append any additional form data directly to the document.
Using the same form posted as above, a jQuery append method could look like:
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 src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<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>
I don't think you can modify the POST vars that way. When a submit handler runs there's no hash of the form data that really exists that you can add to or modify. I think you're right - your only options to $.post() yourself (which I'd recommend) or to append hidden inputs to the form (has the overhead of DOM modification which you don't really need).
I have been working on this question for one day, and I come up with a good solution:
you could use Jquery .clone() to create a copy of the form you want to submit. Then you could do the modifications on the copy, and finally submit the copy.
Attach a submit() handler to the form.
$('form#myForm').submit(myPostHandlingFunction);
Then submit/ do the post from your function. The easiest thing would be to just populate a couple of hidden inputs in the form and then return true to allow the submit to happen if everything looks right.
$("#frm").submit(function (e) {
e.preventDefault();
form = document.getElementById("frm"); //$("#frm")
$.each(form.elements, function (i, el) {
el.name = your_new_name;
el.value = your_new_value;
//... //el.type, el.id ...
});
form.submit();
return true;
});
You can hook the click event of the submit button and do your processing there. For the key/value pairs you might try a hidden form element.
$('#myForm').submit(function() {
$.each(this, function (i, element) {
console.log("element name " + element.name + ", element val: " + element.value);
if(element.name="thisThingInParticular")
element.value = "myNewValueForThisElementInParticular";
)
}
});
精彩评论