使用XMLHttpRequest发送POST数据
我想在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写等价物?
下面的代码演示了如何做到这一点。
var http = new XMLHttpRequest(); var url = "get_data.php"; var params = "lorem=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);
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);
最less使用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); } xhr.open (oFormElement.method, oFormElement.action, true); xhr.send (new FormData (oFormElement)); return false; // Markus had to return true } </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的问题,因为它需要用户点击以提交请求。 但是这对寻求这种简单解决scheme的人来说可能是有用的。
-
这个例子非常简单,不支持
GET
方法。 如果您对更复杂的示例感兴趣,请查看优秀的MDN文档 。 另请参阅有关XMLHttpRequest发布HTML表单的类似答案 。 -
此解决scheme的局限性:正如Justin Blank和Thomas Munk (请参阅他们的评论)指出的,
FormData
不支持IE9和Android 2.3上的默认浏览器。 -
Markus L在他的评论中解释说,为了实际发送
POST
请求,function submitForm()
必须return true
。
没有插件需要!
只要拖动书签栏中的任何链接(即这个链接 )(如果你没有看到它,从浏览器设置启用),然后编辑链接:
并插入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);
就这样! 现在您可以访问任何网站,并在“ 书签栏”中单击该button!
注意:
上面的方法使用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);
我build议寻找fetch
。 这是ES5的等价物,并使用承诺。 它更可读,更容易定制。
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) );
我遇到了类似的问题,使用相同的post和这个链接,我已经解决了我的问题。
var http = new createXMLHttpRequest(); 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);
此链接已完成信息。
这是
application-json
的完整解决scheme:
// Inputs 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', false) 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>
确保您的后端API可以parsingJSON。
例如,在Express JS中:
import bodyParser from 'body-parser' app.use(bodyParser.json())
var util = { getAttribute: function (dom, attr) { if (dom.getAttribute !== undefined) { return dom.getAttribute(attr); } else if (dom[attr] !== undefined) { return dom[attr]; } else { return null; } }, addEvent: function (obj, evtName, func) { //Primero revisar attributos si existe o no. if (obj.addEventListener) { obj.addEventListener(evtName, func, false); } else if (obj.attachEvent) { obj.attachEvent(evtName, func); } else { if (this.getAttribute("on" + evtName) !== undefined) { obj["on" + evtName] = func; } else { obj[evtName] = func; } } }, removeEvent: function (obj, evtName, func) { if (obj.removeEventListener) { obj.removeEventListener(evtName, func, false); } else if (obj.detachEvent) { obj.detachEvent(evtName, func); } else { if (this.getAttribute("on" + evtName) !== undefined) { obj["on" + evtName] = null; } else { obj[evtName] = null; } } }, getAjaxObject: function () { var xhttp = null; //XDomainRequest if ("XMLHttpRequest" in window) { xhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xhttp = new ActiveXObject("Microsoft.XMLHTTP"); } return xhttp; } }; //START CODE HERE. var xhr = util.getAjaxObject(); var isUpload = (xhr && ('upload' in xhr) && ('onprogress' in xhr.upload)); if (isUpload) { util.addEvent(xhr, "progress", xhrEvt.onProgress()); util.addEvent(xhr, "loadstart", xhrEvt.onLoadStart); util.addEvent(xhr, "abort", xhrEvt.onAbort); } util.addEvent(xhr, "readystatechange", xhrEvt.ajaxOnReadyState); var xhrEvt = { onProgress: function (e) { if (e.lengthComputable) { //Loaded bytes. var cLoaded = e.loaded; } }, onLoadStart: function () { }, onAbort: function () { }, onReadyState: function () { var state = xhr.readyState; var httpStatus = xhr.status; if (state === 4 && httpStatus === 200) { //Completed success. var data = xhr.responseText; } } }; //CONTINUE YOUR CODE HERE. xhr.open('POST', 'mypage.php', true); xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); if ('FormData' in window) { var formData = new FormData(); formData.append("user", "aaaaa"); formData.append("pass", "bbbbb"); xhr.send(formData); } else { xhr.send("?user=aaaaa&pass=bbbbb"); }