AJAX 快速描述
AJAX 只是异步 JSON 或 XML(在大多数较新的情况下为 JSON)。因为我们正在执行异步任务,所以我们可能会为用户提供更愉快的 UI 体验。在本例中,我们使用 AJAX 进行 FORM 提交。
很快就有 4 个常规 Web 操作GET
, POST
, PUT
, and DELETE
;这些直接对应于SELECT/Retreiving DATA
, INSERTING DATA
, UPDATING/UPSERTING DATA
, and 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文档。
Example:使用ajax请求发送表单数据
$.post("test.php", $("#testform").serialize());
Example:使用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 或登录相关的内容)