javascript 使用 vanilla js 提交 ajaxForm 表单
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33021995/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Submit form for ajaxForm with using vanilla js
提问by Chris Muench
I am injecting JS from an iOS app to a web app. I control code for both. I am trying to write javascript that takes input from a barcode scanner and then puts it in a web form and then submits the form. I use the jQuery.formplugin to make all the forms ajax. I use ajaxForm.
我正在将 JS 从 iOS 应用程序注入到 Web 应用程序。我控制两者的代码。我正在尝试编写 javascript,它从条形码扫描仪获取输入,然后将其放入 Web 表单中,然后提交表单。我使用jQuery.form插件来制作所有的表单 ajax。我使用ajaxForm。
I want to make the code as generic as possible in case I change the front-end code down the road (For example removing ajaxForm). My goal is to simply have a set of ids and when it matches an id to changes the value of the input and then submits the form. This form could be ajax or a regular form; but the iOS app should NOT know the implementation details. Is there a way to do this in vanilla js?
我想让代码尽可能通用,以防我更改前端代码(例如删除 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;
}
}
回答by shennan
In order to submit a form using vanilla/plain JS, simply call the submit
method on the form:
为了使用 vanilla/plain JS 提交表单,只需调用submit
表单上的方法:
document.getElementById('formId').submit();
However, it sound like you want to make an AJAX request. These are different from standard HTTP requests. They are called XMLHttp Requests.
但是,听起来您想发出 AJAX 请求。这些不同于标准的 HTTP 请求。它们被称为XMLHttp 请求。
When you submit a form using a plain HTTP request (what happens when you use form.submit()
), the browser populates the POST/GET variables that get sent to the server by using the information inside the <form>
that is being sent.
当您使用普通 HTTP 请求提交表单时(使用 时会发生什么form.submit()
),浏览器会使用<form>
正在发送的 POST/GET 变量中的信息填充发送到服务器的 POST/GET 变量。
When sending an XMLHttp Request, that work is not done for you. You must do it yourself.
发送 XMLHttp 请求时,该工作不会为您完成。你必须自己做。
As far as I can tell, this is the bulk of what jQuery.formis doing. It is collecting the information in your form, populating an XMLHttp Request, and then submitting the form to the server using so-called AJAX technology.
据我所知,这是jQuery.form所做的大部分工作。它收集表单中的信息,填充 XMLHttp 请求,然后使用所谓的 AJAX 技术将表单提交到服务器。
You may find thisanswer useful; someone has written a plain Javascript method for submitting a form via AJAX. Here is the method from that answer:
您可能会发现此答案很有用;有人编写了一个简单的 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);
}
It's probably worth noting that the original poster of this code is using methods that won't work on some older browsers. Notably browsers that do not support the ECMAScript 5implementation.
可能值得注意的是,此代码的原始海报使用的方法在某些较旧的浏览器上不起作用。特别是不支持ECMAScript 5实现的浏览器。
My advice would be to stick to using the plugin you already have. I can't see a reason to re-invent the wheel. Rest assured that your jQuery library is using vanilla Javascript under the hood.
我的建议是坚持使用您已有的插件。我找不到重新发明轮子的理由。请放心,您的 jQuery 库在底层使用的是 vanilla Javascript。