ajax Post数据,并得到返回结果,密码加密(Select,checkbox)
使用ajax Post数据到后台Server,并从后台返回数据给前端WEB:
urls.py:
from django.conf.urls import url
from aptest import views as aptest
urlpatterns = [
url(r'^$', aptest.index, name='index'), ]
编辑views.py,定义主页:
from django.views.decorators.csrf import csrf_exempt #导入csrf_exempt模块,在前端POST数据时不检测csrftoken #@csrf_exempt #由于csrf机制,在此需要调用该装饰函数(使POST不检测token),否则在ajax post数据的时候会提示403 forbiddon。如果通过form序列化(serialize)的方式post数据,会自动生成csrftoken,无需调用该装饰函数
@login_req() //要写在csrf_exempt下面,否则不使用form序列化的方式ajax post数据时会提示403 forbiddon
def index(request): #主页
print request.method
a=request.POST.get('a')
b=request.POST.get('b')
print a,b
if a is not None and b is not None:
ret=int(a)+ int(b)
return HttpResponse(str(ret)) #执行到此处,后面的代码不会再继续执行
context={}
return render(request,'aptest/index.html',context)
编辑模板index.html:
在其form中定义action值,指向当前页面,则在ajax post data时无需再定义url,默认将把数据提交到当前页面。
{% extends "base.html" %}
{% block title %}aptest index{% endblock %}
{% block content %}
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="/static/jQuery/index.js"></script> <!--应用的js脚本文件-->
<script > <!--加入这段代码,ajax在POST的时候即可默认提交csrf_token。这段代码必须要放在html文件中,不能放到调用的.js文件中-->
$.ajaxSetup({
data: {csrfmiddlewaretoken: '{{ csrf_token }}' },
});
</script>
<p>请输入两个数字</p>
<form action="{% url 'aptest:index' %}" > <! -- 此处action表示该form提交到的页面,此处含义为 aptest应用的index页面。如果action为空,则需要在ajax post的url中进行定义。action默认留空即表示提交给当前页面,ajax post url也不需要再定义。 method="POST"不需要定义,在ajax里面定义即可 -->
{% csrf_token %}
a: <input type="text" id="a" name="a" > <br>
b: <input type="text" id="b" name="b"> <br> <p>result: <span id='result'></span></p>
<input type="button" id='sum' name='sum' value="cacl">
</form>
<div id="box"></div> {% endblock %}
base.html:
{% include 'header.html' %}
<title>{% block title %}{% endblock %}</title>
</head>
<body>
{% include 'userauth.html' %}
<h1>My Test site</h1>
{% block content %}{% endblock %}
{% block footer %}
<hr>
<p>Thanks for visiting my site2.</p>
{% endblock %}
<!-- {% include 'footer.html' %} -->
</body>
</html>
header.html:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
编辑index.js,定义js函数:
$(document).ready(function(){
$('p').css('color','red')
$('form input[type=button]').click(function(){ //绑定form中tpye=button的input标签
a=$('form input[name=a]').val();
b=$('form input[name=b]').val();
// alert(a);
//alert(b);
$.ajax({
type: 'POST',
//url: '/aptest/', 由于在index.html的form的action已经定义了该url,所以此处不需要再定义。 这段js代码如果直接写在index.html中,则该url也如此,不变。需要注意最后面必须要有/
data: {
a:a,
b:b
},
success:function(response,stutas,xhr){
$('#result').html(response); //将index view的返回值绑定到id=result的内容中。response参数表示所有从后端返回的值
alert(stutas); //执行成功返回状态success
},
error:function(xhr,errorText,errorStatus){
alert(xhr.status+':'+xhr.statusText); //数据提交失败返回403 forbidden
}
});
});
执行结果:提交a=22,b=3,result返回25

index.js提交数据等待,超时:
$(document).ready(function(){
$('p').css('color','red')
$('.loading').css('display','none') //隐藏名为.loading的类
$('#formnum input[type=button]').click(function(){ //选择id=formnum的form中的元素
$.ajax({
type: 'POST',
//url: '/aptest/',
// data: {
// a:a,
// b:b
// },
data:$('#formnum').serialize(), //将id=formnum的form中提交的数据以序列化的方式进行提交,无需再具体写出form中每个input中的内容
success:function(response,stutas,xhr){
$('#result').html(response);
//alert(stutas);
},
error:function(xhr,errorText,errorStatus){
alert(xhr.status+':'+xhr.statusText);
},
timeout:500 //设置超时时间,单位毫秒,超过500ms没有返回结果则报错
});
});
$(document).ajaxStart(function(){ //ajax提交数据时显示等待信息
$('.loading').show(); //.loading是在index.html中定义的class
}).ajaxStop(function(){
$('.loading').hide();
});
});
index view打印request.POST内容如下,可以正常接收数据:
<QueryDict: {u'a': [u'33'], u'csrfmiddlewaretoken': [u'5foMcNoH0cALQ0xoK5NKsyYhSLlCdi88'], u'b': [u'2']}>
index.html编辑如下:
{% extends "base.html" %}
{% block title %}aptest index{% endblock %}
{% block content %}
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="/static/jQuery/index.js"></script>
<p>请输入两个数字</p>
<form id="formnum" action="{% url 'aptest:index' %}" >
{% csrf_token %}
a: <input type="text" id="a" name="a" > <br><br>
b: <input type="text" id="b" name="b"> <br>
<p>result: <span id='result'></span></p>
<input type="button" id='sum' name='sum' value="cacl">
</form><br>
<span class="loading">正在加载中...</span>
<div id="box"></div>
{% endblock %}
执行显示如下:

ajax返回多个值(json格式):
index.js编辑如下:
$(document).ready(function(){
$('p').css('color','red')
$('.loading').css('display','none') //隐藏名为.loading的类
$('#formnum input[type=button]').click(function(){
$.ajax({
type: 'POST',
//url: '/aptest/',
data:$('#formnum').serialize(),
dataType:'json', //定义需要返回json格式,如无特殊需要不要定义dataType,否则当放回的数据不是json格式,则无法正常返回数据
success:function(response,stutas,xhr){
alert(response); //返回Object Object ,从index view response的数据为:rets=[{'r1':PLUS,'r2':MuLT}]。如果返回的数据类型与前面dataType指定的格式不同,则会执行error函数
$('#result').html(response[0].r1); //r1,r2是从view的rets中取来的key值
$('#result2').html(response[0].r2);
//alert(stutas);
},
error:function(xhr,errorText,errorStatus){
alert(xhr.status+' error: '+xhr.statusText);
},
timeout:500
});
});
$(document).ajaxStart(function(){
$('.loading').show();
}).ajaxStop(function(){
$('.loading').hide();
});
// $('input').click(function(){ //点击按钮后再加载test.js文件,而不是全局调用
// $.getScript('test.js');
// });
});
index view:
@csrf_exempt
def index(request): #主页
print request.method
import json
a=request.POST.get('a')
b=request.POST.get('b')
if a is not None and b is not None:
PLUS=int(a) + int(b)
MuLT=int(a) * int(b)
rets=[{'r1':PLUS,'r2':MuLT}] #jQuery只能接受这种类型json数据,不加中括号也可以,直接将dict转换为json格式,js中也就不再需要加index去取值
retsj=json.dumps(rets) #将pathon对象转换为json字符串(str),jQuery只能接受这种类型json数据
return HttpResponse(retsj)
context={}
return render(request,'aptest/index.html',context)
index.html:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="/static/jQuery/index.js"></script> <p>请输入两个数字</p>
<form id="formnum" action="{% url 'aptest:index' %}" >
{% csrf_token %}
a: <input type="text" id="a" name="a" > <br><br>
b: <input type="text" id="b" name="b"> <br> <p>plus: <span id='result'></span></p>
<p>multi: <span id='result2'></span></p>
<input type="button" id='sum' name='sum' value="cacl">
</form><br>
<span class="loading">正在加载中...</span>
执行返回结果:

单选按钮,多选框,下拉列表:
下拉列表参考:http://blog.csdn.net/tiemufeng1122/article/details/44154571
index.html:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="/static/jQuery/index.js"></script> <p>请输入两个数字</p>
<form id="formnum" action="{% url 'aptest:index' %}" >
{% csrf_token %}
a: <input type="text" id="a" name="a" > <br><br>
b: <input type="text" id="b" name="b"> <br><br> <!--定义单选按钮-->
sex: <input type="radio" checked="checked" name="sex" value="man" />男
<input type="radio" name="sex" value="woman" />女<br><br><br> <!--定义复选框-->
<label><input type="checkbox" name="fruit" value="apple" />apple </label>
<label><input type="checkbox" name="fruit" value="pear" />pear </label>
<label><input type="checkbox" name="fruit" value="watermelon" />watermelon </label> <br><br> <!--定义下拉列表-->
Select one:<select id="car" name="car"> <!--index view通过该name名称得到选择结果-->
<option value="Volvo">Volvo</option>
<option value="Saab" selected="selected">Saab</option> <!--默认选中-->
<option value="Mercedes" disabled="disabled">Mercedes</option> <!--不可选,灰色-->
<option value="Audi" title="Audi, your best choice!">Audi</option> <!--鼠标放在上面出现提示信息-->
</select><br> <p>plus: <span id='result'></span></p>
<p>multi: <span id='result2'></span></p> <input type="button" id='sum' name='sum' value="cacl">
</form><br>
<span class="loading">正在加载中...</span>
jquery获得下拉列表的项的属性值: alert(("#car option:selected").text())
jquery获得下拉列表的项的value值: alert(("#car").val())
python后台获得下拉列表的值:
request.GET['car']
如果通过表单序列化方式提交包含有下拉列表的form,提交的时候使用的是select的name,而不是id。如果使用id,后台接收不到该select的值。
index.js:
$(document).ready(function(){
// $('#car').css('color','green') //下拉列表设置为绿色//alert($('input:radio:checked').val()); //获取单选按钮的值
//var arr=[];
//$('input:checkbox:checked').each(function(){arr.push(this.value);}); #获取复选框的值
//alert(arr[0]);
//alert($('#car').val()); //获取下拉列表的值
});
index.view:
#django中需要使用getlist获取复选框的值,使用get只能获取到最后一个值
request.POST.getlist('fruit')
页面显示:

使用jQuery的md5插件对密码进行加密处理。后台通过request.POST.get('name'),request.POST.get('pwd')进行接收。
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="/static/jQuery/jQuery.md5.js"></script>
<script>
$(document).ready(function(){
$('#login').click(function(){
var name = $('#uname').val();
var pass = $('#formlogin input[type=password]').val();
var passmd5 = $.md5(pass);
//alert(passmd5+name); $.ajax({
type: 'POST',
url: '/aptest/login/',
data:{
name:name,
pwd:passmd5
},
timeout:500
}); });
}) </script>
检查字符串name的长度:alert(name.length)
查看数据类型:alert($.type(name))
判断字符串name是否包含数字:
var pattern = /\d/ig; //var pattern = /[a-z]+/ig; 检查是否包含有字母
if(pattern.test(name))
{alert(number)}
else{alert('nonono')};
return; 将终止函数执行,return后面的语句均不会再被执行。
ajax POST数组(array)到后台:
var datas_del = []
datas_del.push(pk_del); $.ajax({
type: 'POST',
traditional :true, //需要加上该句,否则在post到后台时,key值为datas_del[],后面多了一个[]
data:{datas_del:datas_del},
dataType:'json',
success:function(response,stutas,xhr){
alert(response.sts);
//alert(stutas);
},
error:function(xhr,errorText,errorStatus){
alert(xhr.status+' error: '+xhr.statusText);
},
timeout:500
});
Select说明:
1.获取select 选中的 text:
$("#cusChildTypeId").find("option:selected").text();
$("#cusChildTypeId option:selected").text()
2.获取select选中的 value:
$("#ddlRegType ").val();
3.获取select选中的索引:
$("#ddlRegType ").get(0).selectedIndex;
4.得到select项的个数
$("#cusChildTypeId").get(0).options.length
5.设置select 选中的索引:
$("#cusChildTypeId").get(0).selectedIndex=index;//index为索引值
6.设置select 选中的value:
$("#cusChildTypeId").attr("value","Normal");
$("#cusChildTypeId").val("Normal");
$("#cusChildTypeId").get(0).value = "Normal";
7.设置select 选中的text:
1>.var count=$("#cusChildTypeId").get(0).options.length;
for(var i=0;i<count;i++)
{
if($("#cusChildTypeId").get(0).options.text == text)
{
$("#cusChildTypeId").get(0).options.selected = true;
break;
}
}
2>.$("#cusChildTypeId").val(text);
$("#cusChildTypeId").change();
8.向select中添加一项,显示内容为text,值为value
$("#cusChildTypeId").get(0).options.add(new Option(text,value));
9.删除select中值为value的项
var count = $("#cusChildTypeId").size();
for(var i=0;i<count;i++)
{
if($("#cusChildTypeId").get(0).options[i].value == value)
{
$("#cusChildTypeId").get(0).remove(i);
break;
}
}
10.清空 Select:
1>. $("#cusChildTypeId").empty();
2>. $("#cusChildTypeId").get(0).options.length = 0;
ajax Post数据,并得到返回结果,密码加密(Select,checkbox)的更多相关文章
- 用Nodejs+Express搭建web,nodejs路由和Ajax传数据并返回状态,nodejs+mysql通过ajax获取数据并写入数据库
小编自学Nodejs,看了好多文章发现都不全,而且好多都是一模一样的 当然了,这只是基础的demo,经供参考,但是相信也会有收获 今天的内容是用Nodejs+Express搭建基本的web,然后呢no ...
- [NodeJs] 用Nodejs+Express搭建web,nodejs路由和Ajax传数据并返回状态,nodejs+mysql通过ajax获取数据并写入数据库
小编自学Nodejs,看了好多文章发现都不全,而且好多都是一模一样的 当然了,这只是基础的demo,经供参考,但是相信也会有收获 今天的内容是用Nodejs+Express搭建基本的web,然后呢no ...
- springboot+shiro 02 - 异步ajax请求无权限时,返回json格式数据
博客: https://www.cnblogs.com/youxiu326/p/shiro-01.html github:https://github.com/youxiu326/sb_shiro_s ...
- phpStudy4——前端页面使用Ajax请求并解析php返回的json数据
项目需求: 在html页面显示所有用户列表信息. 需求分析: 1. html页面使用ajax向后端php请求用户数据 2. php脚本查询数据库,并将查询后的结果以json格式返回前端html页面 3 ...
- jQuery——通过Ajax发送数据
Ajax(Asynchronous JavaScript and XML,异步JavaScript和XML),一个Ajax解决方案涉及如下技术: JavaScript:处理与用户及其他浏览器相关事件的 ...
- 扩展auth_user字段、BBS需求分析、创建BBS数据库、注册页面搭建与用户头像展示及Ajax提交数据
昨日内容回顾 csrf跨站请求 1. SQL注入 2. xss攻击 3. csrf跨站请求 4. 密码加密(加盐) '''django中默认有一个中间件来验证csrf''' # 只针对post请求才验 ...
- ajax大数据排队导出+进度条
描述 :我们现在有很多数据,分表存放,现在需要有精度条的导出.最后面有完整源码. 效果图:
- Ajax——ajax调用数据总结
在做人事系统加入批量改动的功能中,须要将前台中的数据传给后台.后台并运行一系列的操作. 通过查询和学习了解到能够通过ajax将值传入到后台,并在后台对数据进行操作. 说的简单点.就是ajax调用后台的 ...
- ajax完成list无刷新返回
ajax完成list无刷新返回 ajax无刷新技术总结,以下是一段我写的ajax应用的js脚本.其中提交的data刚开始我采用的是$('#formId').serialize();但是出现乱码问题,为 ...
随机推荐
- C语言中函数返回字符串的四种方法
在讨论着四种方法之前,首先要对函数有一个简单的认识,无论是在形实结合时,还是在return语句返回时,都有一个拷贝的过程.你传进来的参数是个值,自然函数在工作之前要把这个值拷贝一份供自己使用,你传进来 ...
- SpringMVC源码阅读:Controller中参数解析
1.前言 SpringMVC是目前J2EE平台的主流Web框架,不熟悉的园友可以看SpringMVC源码阅读入门,它交代了SpringMVC的基础知识和源码阅读的技巧 本文将通过源码(基于Spring ...
- MCS锁和CLH锁
CLH锁:自旋锁,在上一个节点上等待,先上代码: public class CLHLock { /** * 保证原子性操作 * */ private AtomicReference<Node&g ...
- tcpdump一个命令的剖析
简单介绍:用简单的话来定义tcpdump,就是:dump the traffic on a network,根据使用者的定义对网络上的数据包进行截获的包分析工具. tcpdump可以将网络中传送的数据 ...
- [C语言] 数据结构-算法效率的度量方法-事前分析估算方法
事前分析估算方法:在计算机程序编制前,依据统计方法对算法进行估算,抛开与计算机硬件软件有关的因素,一个程序的运行时间,依赖于算法的,好坏和问题的输入规模,所谓问题输入规模是指输入量的多少 推导过程,比 ...
- ios app真正的相互!!调用
1.需求:A应用打开B.B回跳到A 2.问题: 看到网络上的文档讲的大多数都是app单向跳转的例子,而我们在跳转到第二个app的时候往往需要返回到原来的app,虽然支付宝微信等第三方等应用会有回调 ...
- Android Studio 1.1.0汉化初步出炉!
我找到去年12月国人汉化的版本,然后迁移上来的.实测支持Android window最新版(1.1.0) 项目分4部分:1压缩好的:2文本分析器:3原生的语言包:4原版语言包备份 现在一些新增的项目没 ...
- 【转】启动tomcat的时候一直卡在INFO: Deploying web application
在用centos7.+不熟tomcat项目的时候,启动时突然很奇怪的没报错,但是又访问不了网址,调用./shutdown.sh又结束不了,一直出现: java.net.ConnectException ...
- 算法 - Catalan数 (卡特兰)
http://blog.csdn.net/linhuanmars/article/details/24761459 https://zh.wikipedia.org/wiki/%E5%8D%A1%E5 ...
- listview更改选中时item背景色(转)
默认情况下使用ListView背景色是黑色,选中item的高亮颜色是菊黄色,很多时候不得不自己定义背景色或者背景图 android:cacheColorHint="@android:colo ...