使用vanilla js提交ajaxForm的表单

Chr*_*nch 3 javascript forms ajax jquery

我正在从一个iOS应用程序注入JS到一个Web应用程序.我控制两者的代码.我正在尝试编写从条形码扫描器获取输入的javascript,然后将其放入Web表单然后提交表单.我使用jQuery.form插件制作所有表单ajax.我用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;
    }
}
Run Code Online (Sandbox Code Playgroud)

she*_*nan 8

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

document.getElementById('formId').submit();
Run Code Online (Sandbox Code Playgroud)

但是,听起来你想要发出一个AJAX请求.这些与标准HTTP请求不同.它们被称为XMLHttp请求.

当您使用普通HTTP请求(使用时会发生什么form.submit())提交表单时,浏览器会使用<form>正在发送的信息填充发送到服务器的POST/GET变量.

发送XMLHttp请求时,不会为您完成这项工作.你必须自己做.

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

你会发现这个答案很有用; 有人编写了一个简单的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);
}
Run Code Online (Sandbox Code Playgroud)

值得注意的是,此代码的原始海报使用的方法不适用于某些旧版浏览器.特别是不支持ECMAScript 5实现的浏览器.

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