gpt4 book ai didi

javascript - 使用ajax提交表单

转载 作者:技术小花猫 更新时间:2023-10-29 12:08:59 24 4
gpt4 key购买 nike

我正在开发一个应用程序(我大学的一种社交网络)。我需要添加评论(在特定数据库中插入一行)。为此,我的 html 页面中有一个包含各种字段的 HTML 表单。在提交时我不使用表单的操作,但我使用自定义 javascript 函数在提交表单之前详细说明一些数据。

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;

关于javascript - 使用ajax提交表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13611614/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com