[英]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.