使用ajax提交表单

Ale*_*ani 17 html javascript ajax jquery

我正在开发一个应用程序(我的大学的一种社交网络).我需要添加注释(在特定数据库中插入一行).为此,我在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();
}
Run Code Online (Sandbox Code Playgroud)

最后一行将表单提交到正确的页面.它工作正常.但我想使用ajax提交表单,我不知道如何做到这一点,因为我不知道如何捕获表单输入值.有人可以帮帮我吗?

ins*_*ner 28

实际上没有人给出一个纯粹的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;
    }
Run Code Online (Sandbox Code Playgroud)

在你的情况下:

var var_str = "video_time=" + document.getElementById('video_time').value 
     + "&video_id=" + document.getElementById('video_id').value;
Run Code Online (Sandbox Code Playgroud)


Dav*_*ler 21

关于什么

$.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) { ... },
});
Run Code Online (Sandbox Code Playgroud)


pmr*_*ule 10

您可以在提交按钮中添加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>
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你.


Kam*_*ski 10

您可以使用 FormData 捕获表单输入值并通过 fetch 发送它们

fetch(form.action,{method:'post', body: new FormData(form)});
Run Code Online (Sandbox Code Playgroud)

fetch(form.action,{method:'post', body: new FormData(form)});
Run Code Online (Sandbox Code Playgroud)
function send(e,form) {
  fetch(form.action,{method:'post', body: new FormData(form)});

  console.log('We send post asynchronously (AJAX)');
  e.preventDefault();
}
Run Code Online (Sandbox Code Playgroud)


Mac*_*was 5

这是一个通用的解决方案,它遍历表单中的每个字段并自动创建请求字符串。它正在使用新的提取API。自动读取表单属性:methodaction并获取表单内的所有字段。支持一维数组字段,例如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>
Run Code Online (Sandbox Code Playgroud)