需要使用 xhr.send(); 参数为请求数据体, 如果没有就传入null, 一般来说, GET请求是不用传参的, POST就视情况而定, 理论上所有GET请求都可以改为POST, 反之则不行.
var xhr = new XMLHttpRequest(); xhr.open('GET', 'http://www.example.com/?id=' + encodeURIComponent(id), true ); xhr.send(null);
下面是POST请求的示例:
var xhr = new XMLHttpRequest(); var data = 'email=' + encodeURIComponent(email) + '&password=' + encodeURIComponent(password); xhr.open('POST', 'http://www.example.com', true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.send(data);
注意:
1. 所有xhr的监听事件都必须在xhr.send()方法调用之前声明;
2. xhr.send()的参数类型支持多种, 比如: null / ArrayBufferView / Blob / Document / String / FormData;