FormData()方法 ——将数据以Key=value 的方式通过XMLHttpRequest对象发送给服务器
注:
一、无form标签时:
var 对象名 = new FormData();
对象名.append(‘key’,value);
二、有form标签时:
var 对象名= new FormData(表单对象);
元素的name自动转换为key;
html代码
<div>
邮箱: <input type="text" id="txtEmail">
</div>
<div>
密码: <input type="password" id="txtPassword">
</div>
<button>登录</button>
JS部分代码
window.onload = function(e){
var btnLogin = document.querySelector('button');
var txtEmail = document.querySelector('#txtEmail');
var txtPassword = document.querySelector('#txtPassword');
btnLogin.onclick = function(e){
// var parameters = 'email=' + txtEmail.value + '&password=' + txtPassword.value;
var frmData = new FormData();
frmData.append('email' , txtEmail.value);
frmData.append('password' , txtPassword.value);
var xhr = new XMLHttpRequest();
xhr.open('POST' , 'http://192.168.7.100/herowebapi/member/login' , true);
// xhr.setRequestHeader('content-type' , 'application/x-www-form-urlencoded');
xhr.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
console.log(this.responseText);
}
}
// xhr.send(parameters);
xhr.send(frmData);
};
}
有form标签时
window.onload = function(e){
var btnLogin = document.querySelector('button');
var form = document.querySelector('form');
btnLogin.onclick = function(e){
var frmData = new FormData(form);
var xhr = new XMLHttpRequest();
xhr.open('POST' , 'http://192.168.7.100/herowebapi/member/login' , true);
xhr.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
console.log(this.responseText);
}
}
xhr.send(frmData);
};
}