ajax XMLHttpRequest 发布 HTML 表单
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18592679/
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
XMLHttpRequest to Post HTML Form
提问by StuStirling
Current Setup
当前设置
I have an HTML form like so.
我有一个像这样的 HTML 表单。
<form id="demo-form" action="POST" method="post-handler.php">
<input type="text" name="name" value="previousValue"/>
<button type="submit" name="action" value="dosomething">Update</button>
</form>
I may have many of these forms on a page.
我可能在一个页面上有很多这样的表格。
My Question
我的问题
How do I submit this form asynchronously and not get redirected or refresh the page? I know how to use XMLHttpRequest. The issue I have is retrieving the data from the HTML in javascript to then put into a post request string. Here is the method I'm currently using for my zXMLHttpRequest`'s.
如何异步提交此表单而不被重定向或刷新页面?我知道如何使用XMLHttpRequest. 我遇到的问题是从 javascript 中的 HTML 中检索数据,然后将其放入发布请求字符串中。这是我目前用于 zXMLHttpRequest` 的方法。
function getHttpRequest() {
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlhttp;
}
function demoRequest() {
var request = getHttpRequest();
request.onreadystatechange=function() {
if (request.readyState == 4 && request.status == 200) {
console.log("Response Received");
}
}
request.open("POST","post-handler.php",true);
request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
request.send("action=dosomething");
}
So for example, say the javascript method demoRequest()was called when the form's submit button was clicked, how do I access the form's values from this method to then add it to the XMLHttpRequest?
例如,假设在demoRequest()单击表单的提交按钮时调用了 javascript 方法,我如何从该方法访问表单的值,然后将其添加到XMLHttpRequest?
EDIT
编辑
Trying to implement a solution from an answer below I have modified my form like so.
试图从下面的答案中实现解决方案,我已经像这样修改了我的表单。
<form id="demo-form">
<input type="text" name="name" value="previousValue"/>
<button type="submit" name="action" value="dosomething" onClick="demoRequest()">Update</button>
</form>
However, on clicking the button, it's still trying to redirect me (to where I'm unsure) and my method isn't called?
但是,在单击按钮时,它仍然试图将我重定向(到我不确定的地方)并且我的方法没有被调用?
Button Event Listener
按钮事件监听器
document.getElementById('updateBtn').addEventListener('click', function (evt) {
evt.preventDefault();
// Do something
updateProperties();
return false;
});
回答by ComFreek
The POST string format is the following:
POST 字符串格式如下:
name=value&name2=value2&name3=value3
So you have to grab all names, their values and put them into that format.
You can either iterate all input elements or get specific ones by calling document.getElementById().
因此,您必须获取所有名称、它们的值并将它们放入该格式。您可以迭代所有输入元素或通过调用获取特定元素document.getElementById()。
Warning:You have to use encodeURIComponent()for all names and especially for the values so that possible &contained in the strings do not break the format.
警告:您必须使用encodeURIComponent()所有名称,尤其是值,以便&字符串中可能包含的内容不会破坏格式。
Example:
例子:
var input = document.getElementById("my-input-id");
var inputData = encodeURIComponent(input.value);
request.send("action=dosomething&" + input.name + "=" + inputData);
Another far simpler option would be to use FormDataobjects. Such an object can hold name and value pairs.
另一个更简单的选择是使用FormData对象。这样的对象可以保存名称和值对。
Luckily, we can construct a FormDataobject from an existing form and we can send it it directly to XMLHttpRequest's method send():
幸运的是,我们可以FormData从现有的表单构造一个对象,我们可以将它直接发送到XMLHttpRequest的方法send():
var formData = new FormData( document.getElementById("my-form-id") );
xhr.send(formData);
回答by olibre
The ComFreek's answeris correct but a complete example is missing.
该ComFreek的答案是正确的,但一个完整的例子丢失。
Therefore I have wrote an extremely simplified working snippet:
因此我写了一个极其简化的工作片段:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge, chrome=1"/>
<script>
"use strict";
function submitForm(oFormElement)
{
var xhr = new XMLHttpRequest();
xhr.onload = function(){ alert(xhr.responseText); }
xhr.open(oFormElement.method, oFormElement.getAttribute("action"));
xhr.send(new FormData(oFormElement));
return false;
}
</script>
</head>
<body>
<form method="POST"
action="post-handler.php"
onsubmit="return submitForm(this);" >
<input type="text" value="previousValue" name="name"/>
<input type="submit" value="Update"/>
</form>
</body>
</html>
This snippet is basic and cannot use GET. I have been inspired from the excellent Mozilla Documentation. Have a deeper read of this MDN documentation to do more. See also this answer using formAction.
此代码段是基本的,不能使用GET. 我从优秀的Mozilla 文档中得到了启发。深入阅读此 MDN 文档以完成更多工作。另请参阅此答案使用formAction.
回答by Awais Qarni
By the way I have used the following code to submit form in ajax request.
顺便说一句,我使用以下代码在ajax请求中提交表单。
$('form[id=demo-form]').submit(function (event) {
if (request) {
request.abort();
}
// setup some local variables
var $form = $(this);
// let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
// serialize the data in the form
var serializedData = $form.serialize();
// fire off the request to specific url
var request = $.ajax({
url : "URL TO POST FORM",
type: "post",
data: serializedData
});
// callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
});
// callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
});
// callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// reenable the inputs
});
// prevent default posting of form
event.preventDefault();
});
回答by Zlatko
With pure Javascript, you just want something like:
使用纯 Javascript,您只需要以下内容:
var val = document.getElementById("inputFieldID").value;
You want to compose a dataobject that has key-value pairs, kind of like
你想组合一个具有键值对的数据对象,有点像
name=John&lastName=Smith&age=3
Then send it with request.send("name=John&lastName=Smith&age=3");
然后用request.send("name=John&lastName=Smith&age=3");发送它。
回答by Worik
I have had this problem too, I think.
我也有这个问题,我想。
I have a input element with a button. The onclickmethod of the button uses XMLHTTPRequestto POST a request to the server, all coded in the JavaScript.
我有一个带按钮的输入元素。onclick按钮的方法用于XMLHTTPRequest向服务器发送请求,所有这些都用 JavaScript 编码。
When I wrapped the input and the button in a form the form's action property was used. The button was nottype=submitwhich form my reading of HTML standard (https://html.spec.whatwg.org/#attributes-for-form-submission) it should be.
当我将输入和按钮包装在表单中时,使用了表单的 action 属性。该按钮不是type=submit我阅读 HTML 标准 ( https://html.spec.whatwg.org/#attributes-for-form-submission) 的形式。
But I solved it by overriding the form.onsubmitmethod like so:
但是我通过form.onsubmit像这样覆盖方法来解决它:
form.onsubmit = function(E){return false;}
I was using FireFox developer edition and chromium 38.0.2125.111 Ubuntu 14.04 (290379) (64-bit).
我使用的是 FireFox 开发者版和 Chromium 38.0.2125.111 Ubuntu 14.04 (290379)(64 位)。
回答by Sahil Anand
function postt(){
var http = new XMLHttpRequest();
var y = document.getElementById("user").value;
var z = document.getElementById("pass").value;
var postdata= "username=y&password=z"; //Probably need the escape method for values here, like you did
http.open("POST", "chat.php", true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", postdata.length);
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(postdata);
}
how can I post the values of y and z here from the form
我如何从表单中发布 y 和 z 的值

