http://www.cnblogs.com/wupeiqi/articles/5703697.html
Ajax
# jQuery使用Ajax
$.ajax({
url: '/index/', #数据要发送到的url
type: 'POST', #请求类型
data: {'username': 'alex','password': '123'}, # 要发送的数据
dataType: 'json', # 告诉浏览器后台返回的数据是json类型,jQuery会自动将后台接收到的字符串转换成字典------如果不写这一行就需要自己将字符串反序列化为字典(JSON.parse(xxx))
success: function(data){ # 回调函数
// 当后台return之后,该函数自动执行
// data就是后台返回的数据(data是字符串类型)
//一般情况下前后端使用字典进行交流,即前端向后端发送字典,后端处理后,也向前端发送字典,但是由于后端只能想前端发送字符串,所以就需要用JSON来传数据
}
})
示例:
mysite
app01
- views.py
def ajax(request):
ret = {'status': False, 'message': ''}
if request.method == 'POST':
user = request.POST.get('username', None)
pwd = request.POST.get('password', None)
print(user, pwd)
if user == 'alex' and pwd == '123':
ret['status'] = True
return HttpResponse(json.dumps(ret)) #HttpResponse只能传字符串,所以需要将字典用json序列化为字符串
else:
ret['message'] = "用户名或密码错误"
return HttpResponse(json.dumps(ret))
return render(request, 'ajax.html')
templates
- ajax.html
<div>
<p>用户名:<input type="text" id="username" /></p>
</div>
<div>
<p>密码:<input type="password" id="password" /></p>
</div>
<div>
<input type="button" value="提交" onclick="SubmitForm();" />
</div>
<script src="/static/js/jquery-1.12.4.js"></script>
<script>
function SubmitForm() {
$.ajax({
url: '/web/ajax/',
type: 'POST',
data: {'username': $('#username').val(), 'password': $('#password').val()},
dataType: 'json',
success: function(data) {
//var d = JSON.parse(data); #将获得的字符串用json反序列化为字典
if(data.status){
alert('登录成功');
}
else {
alert('登录失败:'+data.message);
}
}
});
}
</script>
Ajax:
1、XMLHttpRequest对象(原生Ajax)
2、jQuery - XMLHttpRequest对象(jQuery ajax)
3、跨域Ajax
浏览器同源策略:
Ajax,只能给自己的域名发请求
跨域名,浏览器做拦截