|
|
Basic usage of .ajax would look something like this:
HTML:- <form id="foo">
- <label for="bar">A bar</label>
- <input id="bar" name="bar" type="text" value="" />
- <input type="submit" value="Send" />
- </form>
复制代码 JavaScript:- // variable to hold request
- var request;
- // bind to the submit event of our form
- $("#foo").submit(function(event){
- // abort any pending request
- if (request) {
- request.abort();
- }
- // setup some local variables
- var $form = $(this);
- // let's select and cache all the fields
- var $inputs = $form.find("input, select, button, textarea");
- // serialize the data in the form
- var serializedData = $form.serialize();
- // let's disable the inputs for the duration of the ajax request
- $inputs.prop("disabled", true);
- // fire off the request to /form.php
- request = $.ajax({
- url: "/form.php",
- type: "post",
- data: serializedData
- });
- // callback handler that will be called on success
- request.done(function (response, textStatus, jqXHR){
- // log a message to the console
- console.log("Hooray, it worked!");
- });
- // callback handler that will be called on failure
- request.fail(function (jqXHR, textStatus, errorThrown){
- // log the error to the console
- console.error(
- "The following error occured: "+
- textStatus, errorThrown
- );
- });
- // callback handler that will be called regardless
- // if the request failed or succeeded
- request.always(function () {
- // reenable the inputs
- $inputs.prop("disabled", false);
- });
- // prevent default posting of form
- event.preventDefault();
- });
复制代码 Note: Since jQuery 1.8, .success, .error and .complete are deprecated in favor of .done, .fail and .always.
PHP (i.e. form.php):- // you can access the values posted by jQuery.ajax
- // through the global variable $_POST, like this:
- $bar = $_POST['bar'];
复制代码 Note: Always sanitize posted data, to prevent injections and other malicious code.
You could also use the shorthand .post in place of .ajax in the above JavaScript code:- $.post('/form.php', serializedData, function(response) {
- // log the response to the console
- console.log("Response: "+response);
- });
复制代码 Note: The above JavaScript is made to work with jQuery 1.8 but should work with previous versions down to jQuery 1.5.
Marcus Ekwall
|
|