JavaScript实现ajax发送表单数据
知识点:
1.重置表单数据
2.获取表单数据(纯JavaScript)
3.设置表单数据(纯JavaScript)
4.ajax发送数据到客户端
(1)设置请求头,自己组合数据
(2)实例化表单对象,不需要设置请求头,数据不需要自己组合
添加案例:
前端样式:
<style> .model{ position: fixed; top: 0px; left: 0px; bottom: 0px; right: 0px; background-color: white; } .hide{ display: none; } </style>
前端html代码:
<div><a onclick="show_form();">添加</a></div> <div class="model hide"> <form method="post" id="add"> <input type="text" name="username" placeholder="username"> <input type="text" name="age" placeholder="age"> <input type="radio" name="gender" value="1" checked>男 <input type="radio" name="gender" value="0">女 <select name="class"> {% for cls in classes %} <option value="{{ cls.id }}">{{ cls }}</option> {% endfor %} </select> <input type="button" onclick="add_stu();" value="添加"> </form> </div> <div> <table border="1"> <thead> <tr> <th>ID</th> <th>姓名</th> <th>年龄</th> <th>性别</th> <th>班级</th> <th>编辑</th> </tr> </thead> <tbody> {% for row in students %} <tr><td>{{ row.id }}</td> <td>{{ row.username }}</td> <td>{{ row.age }}</td> <td> {% if row.gender %} 男 {% else %} 女 {% endif %} </td> <td>{{ row.cls }}</td> <td><a onclick="XhrPostRequest(this);">删除</a>|<a href="/edit_student.html?nid={{ row.id }}">编辑</a></td> </tr> {% endfor %} </tbody> </table> </div>
相关js代码:show_form
function show_form(){ document.getElementsByClassName("model")[0].className = 'model'; }
ajax发送:
function GetXhr(){ if(XMLHttpRequest){ var Xh = new XMLHttpRequest(); }else{ Xh = new ActiveXObject('Microsoft.XMLHTTP'); } return Xh } function add_stu(){ var xhr=GetXhr();
xhr.onreadystatechange = function(){ #只要是状态码发生改变就会触发 var data=xhr.responseText; var ret_dict = JSON.parse(data); if(xhr.readyState==4){ alert(ret_dict['status']) document.getElementById("add").reset(); document.getElementsByClassName("model")[0].className += ' hide'; document.location.reload() } }
//获取text值 var username=document.getElementsByName("username")[0].value; var age = document.getElementsByName('age')[0].value; //var token =document.getElementsByName('csrfmiddlewaretoken')[0].value; var token = "{{ csrf_token }}" //获取radio的表单值 var radio = document.getElementsByName('gender'); var gender=null; for(i=0;i<radio.length;i++){ if(radio[i].checked){ if(i==0) gender=1; else gender=0; } } //获取select表单值 var select=document.getElementsByName('class')[0] var index=select.selectedIndex; var sel_id = select[index].value; //重组数据 var data = "username="+username+"&age="+age+"&gender="+gender+"&class="+sel_id+"&csrfmiddlewaretoken="+token; xhr.open('post','/add_student.html');
#请求头一定要设置 xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset-UTF-8"); xhr.send(data); }
删除案例可看:原生ajax中get和post请求
修改案例:
前端html代码:
<tr>
<td>9</td>
<td>fwa发</td>
<td>23</td>
<td>女</td>
<td>Python工程师</td>
<td><a onclick="XhrPostRequest(this);">删除</a>|<a onclick="show_form_edit(this);">编辑</a></td> </tr>
<style> .model,.model_2{ position: fixed; top: 0px; left: 0px; bottom: 0px; right: 0px; background-color: white; } .hide{ display: none; } </style> <div class="model_2 hide"> <form method="post" id="edit"> <input type="hidden" name="id" value=""> <input type="text" name="username" placeholder="username" value=""> <input type="text" name="age" placeholder="age" value=""> <input type="radio" name="gender" value="1" >男 <input type="radio" name="gender" value="0" >女 <select name="class"> {{% for cls in classes %} <option value="{{ cls.id }}">{{ cls }}</option> {% endfor %} </select> {% csrf_token %} <input type="button" onclick="edit_stu(this);" value="修改"> </form> </div>
js代码:
function GetXhr(){ if(XMLHttpRequest){ var Xh = new XMLHttpRequest(); }else{ Xh = new ActiveXObject('Microsoft.XMLHTTP'); } return Xh }
显示模态对话框,自动添加内容:
//修改表单 function show_form_edit(ths){
#显示编辑框 document.getElementsByClassName("model_2")[0].className = 'model_2';
#获取原来table表格中的数据信息 var id=ths.parentElement.parentElement.childNodes[0].textContent; var username=ths.parentElement.parentElement.childNodes[1].textContent; var age=ths.parentElement.parentElement.childNodes[2].textContent; var gender=ths.parentElement.parentElement.childNodes[3].textContent.trim(); if(gender=="男"){ gender=1; }else{ gender=0; } var classes=ths.parentElement.parentElement.childNodes[4].textContent; #开始修改显示出来的form表单数据 form_edit = document.getElementById("edit"); id_inp = form_edit.firstElementChild; id_inp.value=id; user_inp = id_inp.nextElementSibling; user_inp.value=username; age_inp = user_inp.nextElementSibling; age_inp.value=age; gender_inp1=age_inp.nextElementSibling; if(gender_inp1.value==gender){ gender_inp1.checked=true; } gender_inp2=gender_inp1.nextElementSibling; if(gender_inp2.value==gender){ gender_inp2.checked=true; } sel_inp = gender_inp2.nextElementSibling; for(var i=0;i<sel_inp.length;i++){ if(sel_inp[i].text==classes){ sel_inp[i].selected=true; break; } } }
点击修改,ajax提交数据(使用form对象提交,就不需要请求头设置了,否则设置出错会报错):
//发送表单 function edit_stu(ths){
#实例化表单对象 var form = new FormData();
#开始获取数据 var csrf_ele=ths.previousElementSibling; var sel_ele=csrf_ele.previousElementSibling; var gender_ele = sel_ele.previousElementSibling; if(gender_ele.checked){ var gender=1 } var gender_ele1=gender_ele.previousElementSibling; if(gender_ele1.checked){ var gender=0 } var age_ele = gender_ele1.previousElementSibling; var user_ele = age_ele.previousElementSibling; var id_ele = user_ele.previousElementSibling; #将数据添加到表单对象中,组合发送 form.append('csrfmiddlewaretoken',csrf_ele.value) form.append("class",sel_ele.value) form.append('gender',gender) form.append('age',age_ele.value) form.append('username',user_ele.value) form.append('nid',id_ele.value) var xhr = GetXhr() xhr.onreadystatechange = function () { if(xhr.readyState==4){ alert("提交成功") document.getElementById("edit").reset() document.getElementsByClassName("model_2")[0].className += ' hide'; document.location.reload() } } xhr.open('post','/edit_student.html',true)#不需要设置请求头 xhr.send(form) }
补充:使用jquery获取form表单时:
可以使用:$("#fm").serialize()