django實現(xiàn)前后臺交互實例
本文介紹了django實現(xiàn)前后臺交互實例,分享給大家,希望對大家有所幫助
準備工作:
前端框架:AngularJS+bootstap
數(shù)據(jù)庫: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));
頁面演示:
剛打開頁面如下:

輸入數(shù)據(jù),點擊保存:

后臺查看數(shù)據(jù)庫:

可以看到,已經(jīng)保存在數(shù)據(jù)庫里面了。
這只是個小示例,在此不考慮頁面排版和安全性問題。。。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
python如何實現(xiàn)不用裝飾器實現(xiàn)登陸器小程序
這篇文章主要介紹了python如何實現(xiàn)不用裝飾器實現(xiàn)登陸器小程序,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-12-12
Python中np.random.randint()參數(shù)詳解及用法實例
numpy.random.randint()函數(shù)不僅可以生成一維隨機數(shù)組,也可以生成多維度的隨機數(shù)組,下面這篇文章主要給大家介紹了關于Python中np.random.randint()參數(shù)詳解及用法的相關資料,需要的朋友可以參考下2022-09-09
使用pandas 將DataFrame轉(zhuǎn)化成dict
今天小編就為大家分享一篇使用pandas 將DataFrame轉(zhuǎn)化成dict,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12
Python中使用subprocess庫創(chuàng)建附加進程
這篇文章主要介紹了subprocess庫:Python中創(chuàng)建附加進程的相關知識,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-05-05

