前端样式:
<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请求