使用XMLHttpRequest发送POST数据

使用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编写等效代码?


手掌心
浏览 9006回答 3
3回答

慕田峪4524236

下面的代码演示了如何执行此操作。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 requesthttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');http.onreadystatechange = function() {//Call a function when the state changes.&nbsp; &nbsp; if(http.readyState == 4 && http.status == 200) {&nbsp; &nbsp; &nbsp; &nbsp; alert(http.responseText);&nbsp; &nbsp; }}http.send(params);

三国纷争

var xhr = new XMLHttpRequest();xhr.open('POST', 'somewhere', true);xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');xhr.onload = function () {&nbsp; &nbsp; // do something to response&nbsp; &nbsp; 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 () {&nbsp; &nbsp; // do something to response&nbsp; &nbsp; console.log(this.responseText);};xhr.send(data);
打开App,查看更多内容
随时随地看视频慕课网APP