简体   繁体   English

使用 XMLHttpRequest 发送 POST 数据

[英]Send POST data using XMLHttpRequest

I'd like to send some data using an XMLHttpRequest in JavaScript.我想在 JavaScript 中使用 XMLHttpRequest 发送一些数据。

Say I have the following form in HTML:假设我在 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>

How can I write the equivalent using an XMLHttpRequest in JavaScript?如何在 JavaScript 中使用 XMLHttpRequest 编写等效项?

The code below demonstrates on how to do this.下面的代码演示了如何做到这一点。

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);

In case you have/create an object you can turn it into params using the following code, ie:如果您拥有/创建一个对象,您可以使用以下代码将其转换为参数,即:

var params = new Object();
params.myparam1 = myval1;
params.myparam2 = myval2;

// Turn the data object into an array of URL-encoded key/value pairs.
let urlEncodedData = "", urlEncodedDataPairs = [], name;
for( name in params ) {
 urlEncodedDataPairs.push(encodeURIComponent(name)+'='+encodeURIComponent(params[name]));
}
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');

Or if you can count on browser support you could use FormData :或者,如果您可以依靠浏览器支持,您可以使用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);

Use modern JavaScript!使用现代 JavaScript!

I'd suggest looking into fetch .我建议调查fetch It is the ES5 equivalent and uses Promises.它与 ES5 等效并使用 Promises。 It is much more readable and easily customizable.它更具可读性且易于定制。

 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) );

In Node.js, you'll need to import fetch using:在 Node.js 中,您需要使用以下命令导入fetch

const fetch = require("node-fetch");

If you want to use it synchronously (doesn't work in top scope):如果你想同步使用它(在顶级范围内不起作用):

const json = await fetch(url, optionalOptions)
  .then(response => response.json()) // .text(), etc.
  .catch((e) => {});

More Info:更多信息:

Mozilla Documentation Mozilla 文档

Can I Use (96% Nov 2020)我可以使用吗(2020 年 11 月 96%)

David Walsh Tutorial大卫沃尔什教程

Here is a complete solution with application-json :这是带有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>

Ensure that your Backend API can parse JSON.确保您的后端 API 可以解析 JSON。

For example, in Express JS:例如,在 Express JS 中:

import bodyParser from 'body-parser'
app.use(bodyParser.json())

Minimal use of FormData to submit an AJAX request最少使用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>

Remarks评论

  1. This does not fully answer the OP question because it requires the user to click in order to submit the request.这并不能完全回答 OP 问题,因为它需要用户单击才能提交​​请求。 But this may be useful to people searching for this kind of simple solution.但这可能对寻找这种简单解决方案的人有用。

  2. This example is very simple and does not support the GET method.这个例子很简单,不支持GET方法。 If you are interesting by more sophisticated examples, please have a look at the excellent MDN documentation .如果您对更复杂的示例感兴趣,请查看优秀的MDN 文档 See also similar answer about XMLHttpRequest to Post HTML Form .另请参阅有关XMLHttpRequest to Post HTML Form 的类似答案

  3. Limitation of this solution: As pointed out by Justin Blank and Thomas Munk (see their comments), FormData is not supported by IE9 and lower, and default browser on Android 2.3.此解决方案的局限性:正如Justin BlankThomas Munk所指出的(请参阅他们的评论),IE9 及更低版本以及 Android 2.3 上的默认浏览器不支持FormData

NO PLUGINS NEEDED!无需插件!

Select the below code and drag that into in BOOKMARK BAR ( if you don't see it, enable from Browser Settings ), then EDIT that link :选择以下代码并将其拖入书签栏如果您没有看到它,请从浏览器设置启用),然后编辑该链接:

在此处输入图片说明

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);

That's all!就这样! Now you can visit any website, and click that button in BOOKMARK BAR !现在您可以访问任何网站,然后在书签栏中单击该按钮!


NOTE:笔记:

The above method sends data using XMLHttpRequest method, so, you have to be on the same domain while triggering the script.上述方法使用XMLHttpRequest方法发送数据,因此,触发脚本时必须在同一个域中。 That's why I prefer sending data with a simulated FORM SUBMITTING, which can send the code to any domain - here is code for that:这就是为什么我更喜欢使用模拟的 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); 

I have faced similar problem, using the same post and and this link I have resolved my issue.我遇到了类似的问题,使用相同的帖子和这个链接我已经解决了我的问题。

 var http = new XMLHttpRequest();
 var url = "MY_URL.Com/login.aspx";
 var params = 'eid=' +userEmailId+'&amp;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);

This link has completed information.链接已完成信息。

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");
}

There's some duplicates that touch on this, and nobody really expounds on it.有一些重复涉及到这一点,但没有人真正详细说明。 I'll borrow the accepted answer example to illustrate我将借用公认的答案示例来说明

http.open('POST', url, true);
http.send('lorem=ipsum&name=binny');

I oversimplified this (I use http.onload(function() {}) instead of that answer's older methodology) for the sake of illustration.为了说明起见,我对此进行了过度简化(我使用http.onload(function() {})而不是该答案的旧方法)。 If you use this as-is, you'll find your server is probably interpreting the POST body as a string and not actual key=value parameters (ie PHP won't show any $_POST variables).如果您按原样使用它,您会发现您的服务器可能将 POST 正文解释为字符串,而不是实际的key=value参数(即 PHP 不会显示任何$_POST变量)。 You must pass the form header in to get that, and do that before http.send()必须传入表单标题才能获得它,并在http.send()之前执行此http.send()

http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

If you're using JSON and not URL-encoded data, pass application/json instead如果您使用的是 JSON 而不是 URL 编码的数据,请改为传递application/json

Try to use json object instead of formdata.尝试使用 json 对象而不是 formdata。 below is the code working for me.下面是为我工作的代码。 formdata doesnot work for me either, hence I came up with this solution. 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);
    }
}

This helped me as I wanted to use only xmlHttpRequest and post an object as form data:这对我有帮助,因为我只想使用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 https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_forms_through_JavaScript

Short & modern短而现代

You can catch form input values using FormData and send them by fetch可以使用 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>

Just for feature readers finding this question.仅适用于发现此问题的功能读者。 I found that the accepted answer works fine as long as you have a given path, but if you leave it blank it will fail in IE.我发现只要您有给定的路径,接受的答案就可以正常工作,但是如果您将其留空,它将在 IE 中失败。 Here is what I came up with:这是我想出的:

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));
}

You can you it like so:你可以这样:

post("", {orem: ipsum, name: binny}, function (response) {
    console.log(respone);
})

You can use jquery library and call ajax with POST call as below example:您可以使用 jquery 库并通过POST调用调用 ajax,如下例所示:

function RequestService() {  
  var customerName = document.getElementById("txtCustomerName").value;
  var customerEmail = document.getElementById("txtCustomerEmail").value;
  var customerComment = document.getElementById("txtCustomerComment").value;
  var requestServiceData = { email: customerEmail, name: customerName, comment: customerComment, tenantId: yokohamaTenantId};

  $.ajax({
    url: `${identityBaseURL}api/caruser/request-service`,
    method: "POST",
    dataType: "json",
    data: JSON.stringify(requestServiceData),
    contentType:'application/json',
    success: function (data) {
      console.log(data);
    },
  });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM