标签:
$.ajax({ url: ‘/index/‘, type: ‘POST‘, data: {‘username‘: ‘alex‘,‘password‘: ‘123‘}, success: function(data){ // 当后台return之后,该函数自动执行 // data就是后台返回的数据 } })
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div> <p>用户名:<input type="text" id="username" /></p> </div> <div> <p>用户名:<input type="password" id="pwd" /></p> </div> <input type="button" value="提交" onclick="SubmitForm();" /> <script src="/static/jquery-1.8.2.min.js"></script> <script> function SubmitForm(){ $.ajax({ url: ‘/web/ajax_demo/‘, type: ‘POST‘, data: {‘user‘: $(‘#username‘).val(), ‘pwd‘: $(‘#pwd‘).val()}, dataType: ‘json‘, success: function (data) { // data = 字符串 {status:xx,message:‘‘} // data对象 //var data_dict = JSON.parse(data); if(data.status){ location.href = "http://www.baidu.com"; }else{ alert(data.message); } } }) } </script> </body> </html>
Django中view.py
import json def ajax_demo(request): if request.method == ‘POST‘: ret = {‘status‘:False,‘message‘:‘‘} user = request.POST.get(‘user‘,None) pwd = request.POST.get(‘pwd‘,None) if user == ‘111‘ and pwd == ‘222‘: # return HttpResponse(‘1‘) ret[‘status‘] = True return HttpResponse(json.dumps(ret)) else: # return HttpResponse(‘2‘) ret[‘message‘]=‘用户名或者密码错误!‘ return HttpResponse(json.dumps(ret)) return render(request,‘ajax_demo.html‘)
标签:
原文地址:http://www.cnblogs.com/ernest-zhang/p/5854241.html