html form ajax 提交,Submitting HTML form using Jquery AJAX

濮阳鸿祯
2023-12-01

Quick Description of AJAX

AJAX is simply Asyncronous JSON or XML (in most newer situations JSON). Because we are doing an ASYNC task we will likely be providing our users with a more enjoyable UI experience. In this specific case we are doing a FORM submission using AJAX.

Really quickly there are 4 general web actions GET, POST, PUT, and DELETE; these directly correspond with SELECT/Retreiving DATA, INSERTING DATA, UPDATING/UPSERTING DATA, and DELETING DATA. A default HTML/ASP.Net webform/PHP/Python or any other form action is to "submit" which is a POST action. Because of this the below will all describe doing a POST. Sometimes however with http you might want a different action and would likely want to utilitize .ajax.

My code specifically for you (described in code comments):

/* attach a submit handler to the form */

$("#formoid").submit(function(event) {

/* stop form from submitting normally */

event.preventDefault();

/* get the action attribute from the

element */

var $form = $(this),

url = $form.attr('action');

/* Send the data using post with element id name and name2*/

var posting = $.post(url, {

name: $('#name').val(),

name2: $('#name2').val()

});

/* Alerts the results */

posting.done(function(data) {

$('#result').text('success');

});

posting.fail(function() {

$('#result').text('failed');

});

});

First Name

Last Name

Documentation

Example: Send form data using ajax requests

$.post("test.php", $("#testform").serialize());

Example: Post a form using ajax and put results in a div

/* attach a submit handler to the form */

$("#searchForm").submit(function(event) {

/* stop form from submitting normally */

event.preventDefault();

/* get some values from elements on the page: */

var $form = $(this),

term = $form.find('input[name="s"]').val(),

url = $form.attr('action');

/* Send the data using post */

var posting = $.post(url, {

s: term

});

/* Put the results in a div */

posting.done(function(data) {

var content = $(data).find('#content');

$("#result").empty().append(content);

});

});

Important Note

Without using OAuth or at minimum HTTPS (TLS/SSL) please don't use this method for secure data (credit card numbers, SSN, anything that is PCI, HIPAA, or login related)

 类似资料: