django实现前后台交互实例
作者:zhubaoJay 时间:2022-04-12 20:53:33
本文介绍了django实现前后台交互实例,分享给大家,希望对大家有所帮助
准备工作:
前端框架:AngularJS+bootstap
数据库:sqlite3
前端代码:
index.html
<!DOCTYPE html>
<html>
<head>
<link href="/WebApi/scripts/bootstrap/dist/css/bootstrap.min.css" rel="external nofollow" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="/WebApi/scripts/angular/angular.min.js"></script>
<script type="text/javascript" src="/WebApi/controller/controller.js"></script>
<script type="text/javascript" src="/WebApi/service/service.js"></script>
<title>hello</title>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<h2>hello world!</h2>
<!-- <form role="form"> -->
<table>
<tr>
<td>
<div class="form-group">
<input type="text" class="form-control" id="name"
placeholder="请输入用户名" ng-model="username">
</div>
</td>
</tr>
<tr>
<td>
<div class="form-group">
<input type="passwd" class="form-control" id="name"
placeholder="请输入密码" ng-model="password">
</div>
</td>
</tr>
<tr>
<td>
<button type="button" class="btn btn-primary" ng-click="my_submit()">保存</button>
</td>
</tr>
</table>
<!-- </form>
-->
<p class="text-danger">[[ result ]]</p>
</body>
</html>
controller.js
var app = angular.module("myApp", []);
app.config(
function($interpolateProvider) {
$interpolateProvider.startSymbol('[[');
$interpolateProvider.endSymbol(']]');
})
.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
}]);
app.controller("myCtrl", ["$scope", "service", function($scope, service) {
$scope.result = "";
$scope.my_submit = function() {
console.log($scope.username);
console.log($scope.password);
service.do_save_info($scope.username, $scope.password, function(response){
console.log(response);
$scope.result = response.result;
});
};
}]);
service.js
app.service("service", ["$http", function($http) {
this.do_save_info = function(username, password, callback) {
$http({
method: 'POST',
url: '/do_save_info',
data: {
'username': username,
'password': password
},
headers: {'Content-Type': undefined},
}).success(function(response){
callback(response);
});
};
}]);
后端代码:
urls.py
from django.conf.urls import patterns, include, url
urlpatterns = patterns('app.views',
url(r'^index$', 'index'),
url(r'^/index$', 'index'),
url(r'^$', 'index'),
url(r'^/$', 'index'),
url(r'^do_save_info$', 'do_save_info'),
)
views.py
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponse
from django.views.decorators.csrf import ensure_csrf_cookie, csrf_exempt
import json
import models
# Create your views here.
@ensure_csrf_cookie
def index(request):
return render_to_response('static/index.html',
context_instance=RequestContext(request))
def do_save_info(request):
result = {'result':'save success'}
try:
data = json.loads(request.body)
username = data.get("username", None)
password = data.get("password", None)
models.do_save_info(username, password)
except Exception, e:
result['result'] = 'save error'
return HttpResponse(json.dumps(result))
models.py
#!/bin/python
# -*- coding: utf-8 -*-
import os
import sys
import sqlite3
def do_save_info(username, password):
db_path = os.path.normpath('/home/zhubao/Code/django_code/hello/db.sqlite3')
try:
conn = sqlite3.connect(db_path)
sql = "insert into t_user(username, password) values('%s', '%s')" % (username, password)
conn.execute(sql)
conn.commit()
conn.close()
print 'save success...'
except Exception, e:
print '------', str(e)
try:
conn.close()
except Exception, e:
pass
t_user表结构:
create table t_user(username varchar(255), password varchar(255));
页面演示:
刚打开页面如下:
输入数据,点击保存:
后台查看数据库:
可以看到,已经保存在数据库里面了。
这只是个小示例,在此不考虑页面排版和安全性问题。。。
来源:http://blog.csdn.net/zhubaojay/article/details/64128769
标签:django,前后端交互
0
投稿
猜你喜欢
Python操作Mysql实例代码教程在线版(查询手册)
2024-01-24 17:07:44
三表左连接查询的sql语句写法
2024-01-15 01:54:21
CSS双线边框研究
2009-09-03 12:12:00
Python对象体系深入分析
2022-10-25 11:29:33
css基础教程之序曲
2008-07-23 12:40:00
python多进程下的生产者和消费者模型
2022-05-30 02:37:07
在python代码中加入环境变量的语句操作
2023-03-01 22:58:19
python如何用pyecharts制作词云图
2021-05-16 09:35:46
仿豆瓣分页原型(Javascript版)
2007-11-05 14:04:00
详解javascript常用工具类的封装
2024-05-11 09:36:38
使用shell检查并修复mysql数据库表的脚本
2024-01-27 23:52:35
python实现自动化报表功能(Oracle/plsql/Excel/多线程)
2021-04-02 02:05:02
关于Python3 lambda函数的深入浅出
2023-01-12 09:12:41
MySQL函数Locate的使用详解
2024-01-17 22:59:41
Python Numpy计算各类距离的方法
2022-12-03 13:52:53
Python Pygame实战之打砖块小游戏
2021-04-10 01:41:11
深入理解mysql的自连接和join关联
2024-01-21 11:40:01
两个MySql服务的应用
2024-01-20 11:02:00
SQL Server中读取XML文件的简单做法
2008-12-23 15:29:00
python之PySide2安装使用及QT Designer UI设计案例教程
2023-01-18 06:42:53