【问题标题】:Submit form for ajaxForm with using vanilla js使用 vanilla js 提交 ajaxForm 表单
【发布时间】:2016-01-06 10:36:22
【问题描述】:

我正在将 JS 从 iOS 应用程序注入到 Web 应用程序。我控制两者的代码。我正在尝试编写从条形码扫描仪获取输入然后将其放入 Web 表单然后提交表单的 javascript。我使用jQuery.form 插件来制作所有的表单。我使用 ajaxForm。

我想让代码尽可能通用,以防我以后更改前端代码(例如删除 ajaxForm)。我的目标是简单地拥有一组 id,当它与一个 id 匹配时更改输入的值,然后提交表单。这种形式可以是 ajax 或常规形式;但 iOS 应用程序不应该知道实现细节。有没有办法在 vanilla js 中做到这一点?

var scan_ids = ['item','search'];

for(var k=0;k<scan_ids.length;k++)
{
    var scan_id = scan_ids[k];

    if (document.getElementById(scan_id))
    {
        document.getElementById(scan_id).value = "[SCAN]";

        if (scan_id == "item")
        {
             /*I don't want to do this as I am bound to ajaxSubmit; 
I would rather trigger a form submit and have it use ajaxForm
 that is bound to it. If I do .submit() it ignores the ajaxForm */

            $('#add_item_form').ajaxSubmit({target: "#register_container", beforeSubmit: salesBeforeSubmit, success:itemScannedSuccess});


        $('#add_item_form').submit(); //(WORKS and submits via ajax)
        document.getElementById('add_item_form').submit(); //(SUBMITS; DOES NOT AJAX)
        }

        break;
    }
}

【问题讨论】:

  • 您的问题到底是什么?您是在问是否可以在不使用库/框架的情况下在 vanilla JS 中提交表单?
  • 正确。但我试图在不知道表单或使用 jQuery 的情况下做到这一点。只是一个 id(如果可能的话)。查看 if (scan_id == 'item') 中的最后一个 do 行
  • 抱歉,我之前不明白。好的,所以你想用普通的 JS 提交一个表单,但是通过 AJAX?
  • 我希望它的工作方式与 jQuery 中的 $('#add_item_form').submit(); 完全相同,该表单实际上使用的是 ajaxForm,但我不需要知道它就可以工作。 vanilla js有没有办法像那样工作?
  • 我能问一下你为什么要使用 vanilla JS 来做这件事吗?您实际上将重写一个已经工作的模块。

标签: javascript jquery ajax forms


【解决方案1】:

要使用 vanilla/plain JS 提交表单,只需在表单上调用 submit 方法即可:

document.getElementById('formId').submit();

但是,听起来您想发出 AJAX 请求。这些不同于标准的 HTTP 请求。他们被称为XMLHttp Requests

当您使用纯 HTTP 请求提交表单时(使用 form.submit() 时会发生什么),浏览器使用正在发送的 &lt;form&gt; 中的信息填充发送到服务器的 POST/GET 变量已发送。

当发送一个 XMLHttp 请求时,这项工作并没有为您完成。你必须自己做。

据我所知,这是jQuery.form 所做的大部分工作。它正在收集表单中的信息,填充 XMLHttp 请求,然后使用所谓的 AJAX 技术将表单提交到服务器。

您可能会发现this 的回答很有用;有人编写了一个简单的 Javascript 方法来通过 AJAX 提交表单。这是该答案的方法:

/**
 * Takes a form node and sends it over AJAX.
 * @param {HTMLFormElement} form - Form node to send
 * @param {function} callback - Function to handle onload. 
 *                              this variable will be bound correctly.
 */

function ajaxPost (form, callback) {
    var url = form.action,
        xhr = new XMLHttpRequest();

    //This is a bit tricky, [].fn.call(form.elements, ...) allows us to call .fn
    //on the form's elements, even though it's not an array. Effectively
    //Filtering all of the fields on the form
    var params = [].filter.call(form.elements, function(el) {
        //Allow only elements that don't have the 'checked' property
        //Or those who have it, and it's checked for them.
        return typeof(el.checked) === 'undefined' || el.checked;
        //Practically, filter out checkboxes/radios which aren't checekd.
    })
    .filter(function(el) { return !!el.name; }) //Nameless elements die.
    .filter(function(el) { return !el.disabled; }) //Disabled elements die.
    .map(function(el) {
        //Map each field into a name=value string, make sure to properly escape!
        return encodeURIComponent(el.name) + '=' + encodeURIComponent(el.value);
    }).join('&'); //Then join all the strings by &

    xhr.open("POST", url);
    xhr.setRequestHeader("Content-type", "application/x-form-urlencoded");

    //.bind ensures that this inside of the function is the XHR object.
    xhr.onload = callback.bind(xhr); 

    //All preperations are clear, send the request!
    xhr.send(params);
}

可能值得注意的是,此代码的原始发布者使用的方法不适用于某些旧版浏览器。尤其是不支持 ECMAScript 5 实现的浏览器。

我的建议是坚持使用您已有的插件。我看不出重新发明轮子的理由。请放心,您的 jQuery 库在后台使用的是 vanilla Javascript。

【讨论】:

  • 我在 Chrome 版本 53.0.2785.116(64 位)中对此进行了测试,输入字段 el.checked 等于 false。所以我将这个|| el.type !== 'checkbox' || el.type !== 'radio' 包含在该行中。我不想在没有先发表评论的情况下编辑这篇文章。你会说这样的话,检查typeof(el.checked) === 'undefined' 是必要的吗?
  • 似乎那些.filter(function(el) {...}) 方法需要右括号。第 21,22 行。感谢您的回答!
  • @danfo 很好发现。谢谢
  • !el.disabled 在过滤器中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-09
  • 1970-01-01
  • 2016-06-23
相关资源
最近更新 更多