我想在JavaScript中使用XMLHttpRequest发送一些数据。
说我在HTML中有以下表格:
<form name="inputform" action="somewhere" method="post">
<input type="hidden" value="person" name="user">
<input type="hidden" value="password" name="pwd">
<input type="hidden" value="place" name="organization">
<input type="hidden" value="key" name="requiredkey">
</form>
如何在JavaScript中使用XMLHttpRequest编写等效文件?
答案 0 :(得分:641)
以下代码演示了如何执行此操作。
var http = new XMLHttpRequest();
var url = 'get_data.php';
var params = 'orem=ipsum&name=binny';
http.open('POST', url, true);
//Send the proper header information along with the request
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
答案 1 :(得分:234)
var xhr = new XMLHttpRequest();
xhr.open('POST', 'somewhere', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function () {
// do something to response
console.log(this.responseText);
};
xhr.send('user=person&pwd=password&organization=place&requiredkey=key');
或者如果您依靠浏览器支持,可以使用FormData:
var data = new FormData();
data.append('user', 'person');
data.append('pwd', 'password');
data.append('organization', 'place');
data.append('requiredkey', 'key');
var xhr = new XMLHttpRequest();
xhr.open('POST', 'somewhere', true);
xhr.onload = function () {
// do something to response
console.log(this.responseText);
};
xhr.send(data);
答案 2 :(得分:46)
我建议调查fetch
。它是ES5的等价物并使用Promises。它更易读,更容易定制。
const url = "http://example.com";
fetch(url, {
method : "POST",
body: new FormData(document.getElementById("inputform")),
// -- or --
// body : JSON.stringify({
// user : document.getElementById('user').value,
// ...
// })
}).then(
response => response.text() // .json(), etc.
// same as function(response) {return response.text();}
).then(
html => console.log(html)
);
&#13;
在Node.js中,您需要使用以下内容导入fetch
:
const fetch = require("node-fetch");
如果您想同步使用它(不在顶级范围内工作):
const json = await fetch(url, optionalOptions)
.then(response => response.json()) // .text(), etc.
.catch((e) => {});
更多信息:
答案 3 :(得分:32)
FormData
提交AJAX请求<!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); } // success case
xhr.onerror = function(){ alert (xhr.responseText); } // failure case
xhr.open (oFormElement.method, oFormElement.action, true);
xhr.send (new FormData (oFormElement));
return false;
}
</script>
</head>
<body>
<form method="post" action="somewhere" onsubmit="return submitForm(this);">
<input type="hidden" value="person" name="user" />
<input type="hidden" value="password" name="pwd" />
<input type="hidden" value="place" name="organization" />
<input type="hidden" value="key" name="requiredkey" />
<input type="submit" value="post request"/>
</form>
</body>
</html>
这并不完全回答OP问题,因为它要求用户单击以提交请求。但这对于寻找这种简单解决方案的人来说可能是有用的。
此示例非常简单,不支持GET
方法。如果您对更复杂的示例感兴趣,请查看优秀的MDN documentation。另请参阅similar answer about XMLHttpRequest to Post HTML Form。
此解决方案的局限性:正如Justin Blank和Thomas Munk所指出的那样(请参阅他们的评论),IE9及更低版本以及Android上的默认浏览器不支持FormData
2.3。
答案 4 :(得分:23)
只需拖动 BOOKMARK BAR 中的任何链接(例如THIS LINK)(如果您没有看到它,从浏览器设置启用),然后编辑该链接:
并插入javascript代码:
javascript:var my_params = prompt("Enter your parameters", "var1=aaaa&var2=bbbbb"); var Target_LINK = prompt("Enter destination", location.href); function post(path, params) { var xForm = document.createElement("form"); xForm.setAttribute("method", "post"); xForm.setAttribute("action", path); for (var key in params) { if (params.hasOwnProperty(key)) { var hiddenField = document.createElement("input"); hiddenField.setAttribute("name", key); hiddenField.setAttribute("value", params[key]); xForm.appendChild(hiddenField); } } var xhr = new XMLHttpRequest(); xhr.onload = function () { alert(xhr.responseText); }; xhr.open(xForm.method, xForm.action, true); xhr.send(new FormData(xForm)); return false; } parsed_params = {}; my_params.split("&").forEach(function (item) { var s = item.split("="), k = s[0], v = s[1]; parsed_params[k] = v; }); post(Target_LINK, parsed_params); void(0);
就是这样!现在您可以访问任何网站,然后点击 BOOKMARK BAR 中的该按钮!
上述方法使用XMLHttpRequest
方法发送数据,因此,您必须在触发脚本时位于同一个域中。这就是为什么我更喜欢使用模拟的FORM SUBMITTING发送数据,这可以将代码发送到任何域 - 这里是代码:
javascript:var my_params=prompt("Enter your parameters","var1=aaaa&var2=bbbbb"); var Target_LINK=prompt("Enter destination", location.href); function post(path, params) { var xForm= document.createElement("form"); xForm.setAttribute("method", "post"); xForm.setAttribute("action", path); xForm.setAttribute("target", "_blank"); for(var key in params) { if(params.hasOwnProperty(key)) { var hiddenField = document.createElement("input"); hiddenField.setAttribute("name", key); hiddenField.setAttribute("value", params[key]); xForm.appendChild(hiddenField); } } document.body.appendChild(xForm); xForm.submit(); } parsed_params={}; my_params.split("&").forEach(function(item) {var s = item.split("="), k=s[0], v=s[1]; parsed_params[k] = v;}); post(Target_LINK, parsed_params); void(0);
答案 5 :(得分:22)
以下是
application-json
的完整解决方案:
// Input values will be grabbed by ID
<input id="loginEmail" type="text" name="email" placeholder="Email">
<input id="loginPassword" type="password" name="password" placeholder="Password">
// return stops normal action and runs login()
<button onclick="return login()">Submit</button>
<script>
function login() {
// Form fields, see IDs above
const params = {
email: document.querySelector('#loginEmail').value,
password: document.querySelector('#loginPassword').value
}
const http = new XMLHttpRequest()
http.open('POST', '/login')
http.setRequestHeader('Content-type', 'application/json')
http.send(JSON.stringify(params)) // Make sure to stringify
http.onload = function() {
// Do whatever with response
alert(http.responseText)
}
}
</script>
确保您的Backend API可以解析JSON。
例如,在Express JS中:
import bodyParser from 'body-parser'
app.use(bodyParser.json())
答案 6 :(得分:4)
我遇到了类似的问题,使用相同的帖子而且link我已经解决了我的问题。
var http = new XMLHttpRequest();
var url = "MY_URL.Com/login.aspx";
var params = 'eid=' +userEmailId+'&pwd='+userPwd
http.open("POST", url, true);
// Send the proper header information along with the request
//http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//http.setRequestHeader("Content-Length", params.length);// all browser wont support Refused to set unsafe header "Content-Length"
//http.setRequestHeader("Connection", "close");//Refused to set unsafe header "Connection"
// Call a function when the state
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
此link已完成信息。
答案 7 :(得分:3)
$.getJSON("../Conseiller/EditerDemandeurs_MenuConseiller", {
sIdDdeur: idDdeur
}, function(data, status) {
console.log(data.rows[0].Code_Demandeur);
});
答案 8 :(得分:3)
尝试使用json对象代替formdata。以下是对我有用的代码。 formdata也不适合我,因此我想出了这个解决方案。
var jdata = new Object();
jdata.level = levelVal; // level is key and levelVal is value
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "http://MyURL", true);
xhttp.setRequestHeader('Content-Type', 'application/json');
xhttp.send(JSON.stringify(jdata));
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
}
答案 9 :(得分:1)
仅供特征读者查找此问题。我发现只要您具有给定的路径,可接受的答案就可以正常工作,但是如果将其保留为空白,则在IE中将失败。这是我想出的:
function post(path, data, callback) {
"use strict";
var request = new XMLHttpRequest();
if (path === "") {
path = "/";
}
request.open('POST', path, true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.onload = function (d) {
callback(d.currentTarget.response);
};
request.send(serialize(data));
}
您可以这样子吗:
post("", {orem: ipsum, name: binny}, function (response) {
console.log(respone);
})
答案 10 :(得分:1)
有一些重复的内容,没有人真正地阐述过。我将借用公认的答案示例进行说明
http.open('POST', url, true);
http.send('lorem=ipsum&name=binny');
为说明起见,我对此进行了过度简化(我使用http.onload(function() {})
代替了该答案的旧方法)。如果按原样使用,则会发现服务器可能将POST正文解释为字符串,而不是实际的key=value
参数(即PHP将不会显示任何$_POST
变量)。您必须将表单标题传递进来,然后在http.send()
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
如果您使用的是JSON而非URL编码的数据,请改为传递application/json
答案 11 :(得分:1)
这对我很有帮助,因为我只想使用xmlHttpRequest
并将对象作为表单数据发布:
function sendData(data) {
var XHR = new XMLHttpRequest();
var FD = new FormData();
// Push our data into our FormData object
for(name in data) {
FD.append(name, data[name]);
}
// Set up our request
XHR.open('POST', 'https://example.com/cors.php');
// Send our FormData object; HTTP headers are set automatically
XHR.send(FD);
}
https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_forms_through_JavaScript
答案 12 :(得分:1)
您can使用FormData捕获表单输入值并通过fetch发送它们
fetch(form.action, {method:'post', body: new FormData(form)});
function send() {
let form = document.forms['inputform'];
fetch(form.action, {method:'post', body: new FormData(form)});
}
<form name="inputform" action="somewhere" method="post">
<input value="person" name="user">
<input type="hidden" value="password" name="pwd">
<input value="place" name="organization">
<input type="hidden" value="key" name="requiredkey">
</form>
<!-- I remove type="hidden" for some inputs above only for show them --><br>
Look: chrome console>network and click <button onclick="send()">send</button>