HTML中有form表单时
ajax 原生
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form id="form1" action="http://localhost:8080/" method="post">
用户:<input type="text" name="user" /><br>
密码:<input type="password" name="pass" /><br>
文件:<input type="file" name="f1" /><br>
<input type="submit" value="提交">
</form>
</body>
<script>
let oForm=document.querySelector('#form1');
oForm.onsubmit=function (){
let formdata=new FormData(oForm);
let xhr=new XMLHttpRequest();
xhr.open(oForm.method, oForm.action, true);
xhr.send(formdata);
xhr.onreadystatechange=function (){
if(xhr.readyState==4){
if(xhr.status==200){
alert('成功');
}else{
alert('失败');
}
}
};
return false;
};
</script>
</html>
jquery ajax
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form id="form1" action="http://localhost:8080/" method="post">
用户:<input type="text" name="user" /><br>
密码:<input type="password" name="pass" /><br>
文件:<input type="file" name="f1" /><br>
<input type="submit" value="提交">
</form>
</body>
<script src="jquery.js" charset="utf-8"></script>
<script>
$('#form1').on('submit', function (){
let formdata=new FormData(this);
$.ajax({
url: this.action,
type: this.method,
data: formdata,
processData: false,
contentType: false
}).then(res=>{
alert('成功');
}, res=>{
alert('失败');
});
return false;
});
</script>
</html>
无form表单
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="div1">
用户:<input type="text" id="user" /><br>
密码:<input type="password" id="pass" /><br>
文件:<input type="file" id="f1" /><br>
<input id="btn1" type="button" value="提交">
</div>
</body>
<script>
let oBtn=document.querySelector('#btn1');
oBtn.onclick=function (){
let formdata=new FormData();
formdata.append('username', document.querySelector('#user').value);
formdata.append('password', document.querySelector('#pass').value);
formdata.append('f1', document.querySelector('#f1').files[0]);
//
let xhr=new XMLHttpRequest();
xhr.open('post', 'http://localhost:8080/', true);
xhr.send(formdata);
xhr.onreadystatechange=function (){
if(xhr.readyState==4){
if(xhr.status==200){
alert('成功');
}else{
alert('失败');
}
}
};
};
</script>
</html>