標籤:post char text amp eth logs src enc open
前端樣式:
<style> .model{ position: fixed; top: 0px; left: 0px; bottom: 0px; right: 0px; background-color: white; } .hide{ display: none; } </style>
View Code
前端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請求
JavaScript實現ajax發送表單資料