Javascript 使用XMLHttpRequest发送POST数据

Javascript 使用XMLHttpRequest发送POST数据,javascript,ajax,forms,post,xmlhttprequest,Javascript,Ajax,Forms,Post,Xmlhttprequest,我想用JavaScript中的XMLHttpRequest发送一些数据 假设我有以下HTML格式的表单: 如何使用JavaScript中的XMLHttpRequest编写等效程序?下面的代码演示了如何执行此操作 var http = new XMLHttpRequest(); var url = 'get_data.php'; var params = 'orem=ipsum&name=binny'; http.open('POST', url, true); //Send the

我想用JavaScript中的XMLHttpRequest发送一些数据

假设我有以下HTML格式的表单:



如何使用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]));
}

下面的代码演示了如何执行此操作

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]));
}
或者,如果您可以依靠浏览器支持,您可以使用:

或者,如果您可以依靠浏览器支持,您可以使用:

尽可能少地使用
FormData
提交AJAX请求

“严格使用”;
函数submitForm(of formelement)
{
var xhr=new XMLHttpRequest();
xhr.onload=function(){alert(xhr.responseText);}//成功案例
xhr.onerror=function(){alert(xhr.responseText);}//失败案例
xhr.open(oFormElement.method,oFormElement.action,true);
xhr.send(新FormData(oFormElement));
返回false;
}
评论
  • 这并不能完全回答OP问题,因为它要求用户单击以提交请求。但这可能对寻找这种简单解决方案的人有用

  • 此示例非常简单,不支持
    GET
    方法。如果你对更复杂的例子感兴趣,请看一看优秀的例子。另见

  • 此解决方案的局限性:正如和(参见他们的评论)所指出的,
    FormData
    不受IE9及更低版本的支持,并且是Android 2.3上的默认浏览器

  • 尽可能少地使用
    FormData
    提交AJAX请求
    
    “严格使用”;
    函数submitForm(of formelement)
    {
    var xhr=new XMLHttpRequest();
    xhr.onload=function(){alert(xhr.responseText);}//成功案例
    xhr.onerror=function(){alert(xhr.responseText);}//失败案例
    xhr.open(oFormElement.method,oFormElement.action,true);
    xhr.send(新FormData(oFormElement));
    返回false;
    }
    
    评论
  • 这并不能完全回答OP问题,因为它要求用户单击以提交请求。但这可能对寻找这种简单解决方案的人有用

  • 此示例非常简单,不支持
    GET
    方法。如果你对更复杂的例子感兴趣,请看一看优秀的例子。另见

  • 此解决方案的局限性:正如和(参见他们的评论)所指出的,
    FormData
    不受IE9及更低版本的支持,并且是Android 2.3上的默认浏览器

  • 没有插件需要! 选择以下代码并将其拖动到书签栏中(如果看不到,请从浏览器设置启用),然后编辑该链接:

    就这些现在您可以访问任何网站,并单击书签栏中的该按钮


    注: 上面的方法使用
    XMLHttpRequest
    方法发送数据,因此,触发脚本时必须位于同一域。这就是为什么我更喜欢使用模拟表单提交发送数据,该表单可以将代码发送到任何域-以下是相关代码:

     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); 
    
    没有插件需要! 选择以下代码并将其拖动到书签栏中(如果看不到,请从浏览器设置启用),然后编辑该链接:

    就这些现在您可以访问任何网站,并单击书签栏中的该按钮


    注: 上面的方法使用
    XMLHttpRequest
    方法发送数据,因此,触发脚本时必须位于同一域。这就是为什么我更喜欢使用模拟表单提交发送数据,该表单可以将代码发送到任何域-以下是相关代码:

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

    我也遇到过类似的问题,使用同一个帖子,我已经解决了我的问题

     var http = new XMLHttpRequest();
     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);
    

    这已经完成了信息。

    我在同一篇文章中遇到了类似的问题,我已经解决了这个问题

     var http = new XMLHttpRequest();
     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);
    
    这已完成信息。

    使用现代JavaScript! 我建议查看
    fetch
    。它与ES5相当,使用承诺。它更具可读性,更易于定制

    consturl=”http://example.com";
    获取(url{
    方法:“张贴”,
    正文:新FormData(document.getElementById(“inputform”),
    //或者--
    //正文:JSON.stringify({
    //用户:document.getElementById('user')。值,
    // ...
    // })
    }).那么(
    response=>response.text()/.json()等。
    //与函数(response){return response.text();}相同
    ).那么(
    html=>console.log(html)
    );使用现代JavaScript!
    我建议查看
    fetch
    。它与ES5相当,使用承诺。它更具可读性,更易于定制

    consturl=”http://example.com";
    获取(url{
    方法:“张贴”,
    正文:新FormData(document.getElementById(“inputform”),
    //或者--
    //正文:JSON.stringify({
    //用户:document.getElementById('user')。值,
    // ...
    // })
    }).那么(
    response=>response.text()/.json()等。
    //与函数(response){return response.text();}相同
    ).那么(
    html=>console.log(html)
    
    );这是一个包含
    应用程序json
    的完整解决方案:

    //输入值将被ID抓取
    //return停止正常操作并运行login()
    提交
    函数登录(){
    //表单字段,请参见上面的ID
    常量参数={
    电子邮件:document.querySelector(“#loginEmail”).value,
    密码:document.querySelector(“#loginPassword”).value
    }
    consthttp=newXMLHttpRequest()
    http.open('POST','/login')
    http.setRequestHeader('Content-type','app
    
     var http = new XMLHttpRequest();
     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);
    
    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));
    }
    
    post("", {orem: ipsum, name: binny}, function (response) {
        console.log(respone);
    })
    
    http.open('POST', url, true);
    http.send('lorem=ipsum&name=binny');
    
    http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    
    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);
    }
    
    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);
        }
    }
    
    fetch(form.action, {method:'post', body: new FormData(form)});