AJAX 简介
AJAX 只是异步 JSON 或 XML(在大多数较新的情况下为 JSON)。因为我们正在执行 ASYNC 任务,我们可能会为我们的用户提供更愉快的 UI 体验。在这种特定情况下,我们正在使用 AJAX 进行 FORM 提交。
很快就有 4 个通用网络操作GET
、、、POST
和PUT
;DELETE
这些直接对应于SELECT/Retreiving DATA
, INSERTING DATA
, UPDATING/UPSERTING DATA
, 和DELETING DATA
。默认的 HTML/ASP.Net webform/PHP/Python 或任何其他form
操作是“提交”,这是一个 POST 操作。因此,下面将全部描述如何进行 POST。但是,有时使用 http 您可能需要不同的操作,并且可能希望使用.ajax
.
我专门为您编写的代码(在代码注释中描述):
/* attach a submit handler to the form */
$("#formoid").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get the action attribute from the <form action=""> 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');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="formoid" action="studentFormInsert.php" title="" method="post">
<div>
<label class="title">First Name</label>
<input type="text" id="name" name="name">
</div>
<div>
<label class="title">Last Name</label>
<input type="text" id="name2" name="name2">
</div>
<div>
<input type="submit" id="submitButton" name="submitButton" value="Submit">
</div>
</form>
<div id="result"></div>
文档
来自 jQuery 网站$.post
文档。
示例:使用 ajax 请求发送表单数据
$.post("test.php", $("#testform").serialize());
示例:使用 ajax 发布表单并将结果放入 div
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<form action="/" id="searchForm">
<input type="text" name="s" placeholder="Search..." />
<input type="submit" value="Search" />
</form>
<!-- the result of the search will be rendered inside this div -->
<div id="result"></div>
<script>
/* 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);
});
});
</script>
</body>
</html>
重要的提示
如果不使用 OAuth 或至少 HTTPS (TLS/SSL),请不要将此方法用于安全数据(信用卡号、SSN、任何与 PCI、HIPAA 或登录相关的内容)