JavaScript实现ajax发送表单数据

时间:2022-03-16 10:43:56

知识点:

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="" checked>男
<input type="radio" name="gender" value="">女
<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="">
<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")[].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==){
alert(ret_dict['status'])
document.getElementById("add").reset();
document.getElementsByClassName("model")[].className += ' hide';
document.location.reload()
}
}
//获取text值
var username=document.getElementsByName("username")[].value;
var age = document.getElementsByName('age')[].value;
//var token =document.getElementsByName('csrfmiddlewaretoken')[0].value;
var token = "{{ csrf_token }}"
//获取radio的表单值
var radio = document.getElementsByName('gender');
var gender=null;
for(i=;i<radio.length;i++){
if(radio[i].checked){
if(i==)
gender=;
else
gender=;
}
}
//获取select表单值
var select=document.getElementsByName('class')[]
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></td>
  <td>fwa发</td>
  <td></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="" >男
<input type="radio" name="gender" value="" >女
<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")[].className = 'model_2';
    #获取原来table表格中的数据信息
var id=ths.parentElement.parentElement.childNodes[].textContent;
var username=ths.parentElement.parentElement.childNodes[].textContent;
var age=ths.parentElement.parentElement.childNodes[].textContent;
var gender=ths.parentElement.parentElement.childNodes[].textContent.trim();
if(gender=="男"){
gender=;
}else{
gender=;
}
var classes=ths.parentElement.parentElement.childNodes[].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=;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=
}
var gender_ele1=gender_ele.previousElementSibling;
if(gender_ele1.checked){
var gender=
}
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==){
alert("提交成功")
document.getElementById("edit").reset()
document.getElementsByClassName("model_2")[].className += ' hide';
document.location.reload()
}
}
xhr.open('post','/edit_student.html',true)#不需要设置请求头
xhr.send(form)
}

补充:使用jquery获取form表单时:

可以使用:$("#fm").serialize()