我想在 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 = '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);
如果您有/创建一个对象,您可以使用以下代码将其转换为参数,即:
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])); }