[英]submit the form using ajax
我正在開發一個應用程序(我大學的一種社交網絡)。 我需要添加評論(在特定數據庫中插入一行)。 為此,我的 html 頁面中有一個 HTML 表單,其中包含各種字段。 在提交時我不使用表單的操作,但我使用自定義 javascript function 在提交表單之前詳細說明一些數據。
function sendMyComment() {
var oForm = document.forms['addComment'];
var input_video_id = document.createElement("input");
var input_video_time = document.createElement("input");
input_video_id.setAttribute("type", "hidden");
input_video_id.setAttribute("name", "video_id");
input_video_id.setAttribute("id", "video_id");
input_video_id.setAttribute("value", document.getElementById('video_id').innerHTML);
input_video_time.setAttribute("type", "hidden");
input_video_time.setAttribute("name", "video_time");
input_video_time.setAttribute("id", "video_time");
input_video_time.setAttribute("value", document.getElementById('time').innerHTML);
oForm.appendChild(input_video_id);
oForm.appendChild(input_video_time);
document.forms['addComment'].submit();
}
最后一行將表單提交到正確的頁面。 它工作正常。 但我想使用 ajax 提交表單,但我不知道該怎么做,因為我不知道如何捕獲表單輸入值。 任何人都可以幫助我嗎?
實際上沒有人給出純javascript
答案(根據 OP 的要求),所以這里是:
function postAsync(url2get, sendstr) {
var req;
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
if (req != undefined) {
// req.overrideMimeType("application/json"); // if request result is JSON
try {
req.open("POST", url2get, false); // 3rd param is whether "async"
}
catch(err) {
alert("couldnt complete request. Is JS enabled for that domain?\\n\\n" + err.message);
return false;
}
req.send(sendstr); // param string only used for POST
if (req.readyState == 4) { // only if req is "loaded"
if (req.status == 200) // only if "OK"
{ return req.responseText ; }
else { return "XHR error: " + req.status +" "+req.statusText; }
}
}
alert("req for getAsync is undefined");
}
var var_str = "var1=" + var1 + "&var2=" + var2;
var ret = postAsync(url, var_str) ;
// hint: encodeURIComponent()
if (ret.match(/^XHR error/)) {
console.log(ret);
return;
}
在你的情況下:
var var_str = "video_time=" + document.getElementById('video_time').value
+ "&video_id=" + document.getElementById('video_id').value;
關於什么
$.ajax({
type: 'POST',
url: $("form").attr("action"),
data: $("form").serialize(),
//or your custom data either as object {foo: "bar", ...} or foo=bar&...
success: function(response) { ... },
});
您可以向提交按鈕添加 onclick 函數,但無法通過按 Enter 提交函數。 就我而言,我使用這個:
<form action="" method="post" onsubmit="your_ajax_function(); return false;">
Your Name <br/>
<input type="text" name="name" id="name" />
<br/>
<input type="submit" id="submit" value="Submit" />
</form>
希望能幫助到你。
您可以使用 FormData 捕獲表單輸入值並通過 fetch 發送它們
fetch(form.action,{method:'post', body: new FormData(form)});
function send(e,form) { fetch(form.action,{method:'post', body: new FormData(form)}); console.log('We send post asynchronously (AJAX)'); e.preventDefault(); }
<form method="POST" action="myapi/send" onsubmit="send(event,this)"> <input hidden name="crsfToken" value="a1e24s1"> <input name="email" value="a@b.com"> <input name="phone" value="123-456-789"> <input type="submit"> </form> Look on chrome console>network before 'submit'
這是一個通用解決方案,它遍歷表單中的每個字段並自動創建請求字符串。 它正在使用新的 fetch API。 自動讀取表單屬性: method
和action
並抓取表單內的所有字段。 支持單維數組字段,如emails[]
。 可以作為通用解決方案來輕松管理具有單一事實來源 - html 的許多(可能是動態的)表單。
document.querySelector('.ajax-form').addEventListener('submit', function(e) {
e.preventDefault();
let formData = new FormData(this);
let parsedData = {};
for(let name of formData) {
if (typeof(parsedData[name[0]]) == "undefined") {
let tempdata = formData.getAll(name[0]);
if (tempdata.length > 1) {
parsedData[name[0]] = tempdata;
} else {
parsedData[name[0]] = tempdata[0];
}
}
}
let options = {};
switch (this.method.toLowerCase()) {
case 'post':
options.body = JSON.stringify(parsedData);
case 'get':
options.method = this.method;
options.headers = {'Content-Type': 'application/json'};
break;
}
fetch(this.action, options).then(r => r.json()).then(data => {
console.log(data);
});
});
<form method="POST" action="some/url">
<input name="emails[]">
<input name="emails[]">
<input name="emails[]">
<input name="name">
<input name="phone">
</form>
只使用jQuery會容易得多,因為這只是大學的任務,您不需要保存代碼。
因此,您的代碼將如下所示:
function sendMyComment() {
$('#addComment').append('<input type="hidden" name="video_id" id="video_id" value="' + $('#video_id').text() + '"/><input type="hidden" name="video_time" id="video_time" value="' + $('#time').text() +'"/>');
$.ajax({
type: 'POST',
url: $('#addComment').attr('action'),
data: $('form').serialize(),
success: function(response) { ... },
});
}
我建議將 jquery 用於這種類型的要求。 試試這個
<div id="commentList"></div>
<div id="addCommentContainer">
<p>Add a Comment</p> <br/> <br/>
<form id="addCommentForm" method="post" action="">
<div>
Your Name <br/>
<input type="text" name="name" id="name" />
<br/> <br/>
Comment Body <br/>
<textarea name="body" id="body" cols="20" rows="5"></textarea>
<input type="submit" id="submit" value="Submit" />
</div>
</form>
</div>
$(document).ready(function(){
/* The following code is executed once the DOM is loaded */
/* This flag will prevent multiple comment submits: */
var working = false;
$("#submit").click(function(){
$.ajax({
type: 'POST',
url: "mysubmitpage.php",
data: $('#addCommentForm').serialize(),
success: function(response) {
alert("Submitted comment");
$("#commentList").append("Name:" + $("#name").val() + "<br/>comment:" + $("#body").val());
},
error: function() {
//$("#commentList").append($("#name").val() + "<br/>" + $("#body").val());
alert("There was an error submitting comment");
}
});
});
});
我想添加一種新的純javascript
方法來執行此操作,在我看來,通過使用fetch()
API 更簡潔。 這是一種實現網絡請求的現代方式。 在您的情況下,由於您已經有一個form element
我們可以簡單地使用它來構建我們的請求。
const formInputs = oForm.getElementsByTagName("input");
let formData = new FormData();
for (let input of formInputs) {
formData.append(input.name, input.value);
}
fetch(oForm.action,
{
method: oForm.method,
body: formData
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error.message))
.finally(() => console.log("Done"));
正如您所看到的,它比XMLHttpRequest
使用起來非常干凈且不那么冗長。
如今,使用普通的 'ol JS 來實現這一點要容易得多。
const form = document.querySelector('#your-form'),
data = new URLSearchParams();
for (const pair of new FormData(form)) {
data.append(pair[0], pair[1]);
}
fetch(form.action, {
method: form.method || 'POST',
body: data,
}).then(response => response.json()) // or .text()
.then(data => {
console.log('SUBMITTED', data);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.