最近学习了extjs.练习了extjs和django后台交互涉及的ajax,cookie,csrf token等相关例子。完整实现存放在github.
前段代码片段
Ext.onReady(function(){
Ext.Ajax.on('beforerequest', function (conn, options) {
if (!(/^http:.*/.test(options.url) || /^https:.*/.test(options.url))) {
if(Ext.util.Cookies.get('csrftoken')==null){
Ext.util.Cookies.set('csrftoken','csrftoken')
}
if (typeof(options.headers) == "undefined") {
options.headers = {'X-CSRFToken': Ext.util.Cookies.get('csrftoken')};
} else {
options.headers['X-CSRFToken']=Ext.util.Cookies.get('csrftoken');
}
}
}, this);
});
后台:
@login_required
def app_users_update(request):
logging.info(request)
data = json.loads(request.body.decode("utf-8"))
data=data["data"]
id1=data["id"]
rec=User.objects.get(id=id1)
if data.get("name")!=None:
rec.username=data["name"]
if data.get("email")!=None:
rec.email=data["email"]
if data.get("first")!=None:
rec.first_name=data["first"]
if data.get("last")!=None:
rec.last_name=data["last"]
rec.save()
output={"success":True,"message":"UPDATE new User" +str(rec.id)}
output["data"]={"id":rec.id,"name":str(rec.username),"email":str(rec.email),"first":str(rec.first_name),"last":rec.last_name}
return HttpResponse(json.dumps(output, ensure_ascii=False))