使用 XMLHttpRequest 发送 POST 数据 [英] Send POST data using XMLHttpRequest

查看:140
本文介绍了使用 XMLHttpRequest 发送 POST 数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 JavaScript 中使用 XMLHttpRequest 发送一些数据.

I'd like to send some data using an XMLHttpRequest in JavaScript.

假设我在 HTML 中有以下表单:

Say I have the following form in 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 编写等效的代码?

How can I write the equivalent using an XMLHttpRequest in JavaScript?

推荐答案

下面的代码演示了如何做到这一点.

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, i.e:

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

这篇关于使用 XMLHttpRequest 发送 POST 数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆