AJAX の簡単な説明
AJAX は単に非同期 JSON または XML (ほとんどの新しい状況では JSON) です。ASYNC タスクを実行しているため、ユーザーにより楽しい UI エクスペリエンスを提供できる可能性があります。この特定のケースでは、AJAX を使用して FORM 送信を行っています。
非常にすぐに、4 つの一般的な Web アクション、、、GET
およびがありPOST
ます。これらは、、、およびに直接対応します。デフォルトの HTML/ASP.Net webform/PHP/Python またはその他のアクションは、POST アクションである「送信」です。このため、以下ではすべて POST の実行について説明します。ただし、http を使用すると、別のアクションが必要になる場合があり、.PUT
DELETE
SELECT/Retreiving DATA
INSERTING DATA
UPDATING/UPSERTING DATA
DELETING DATA
form
.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 Web サイト$.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、またはログイン関連のもの) にはこの方法を使用しないでください。