欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python-Flask框架用ajax对数据表实现简单的增删改查

程序员文章站 2022-05-08 08:44:14
...

python-Flask框架用ajax对数据表实现简单的增删改查

以下为代码实现
Blueprint其实本身只是对view上的接口进行了注册,然后整体挂载在app上,Blueprint本身的目的就是组织多模块的平行共存,避免直接在app上注册view,其实更多的只是方便开发和代码的维护,因为最终所有的views上的接口都仍然是直接挂载在app上,其实对应整个应用来说,没有什么明显的区别。
Flask 中的Blueprint不是一个可插拨的应用,因为它不是一个真正的应用,而是一套可以注册 在应用中的操作,并且可以注册多次。

#app.py代码实现
from flask import Flask,render_template,request,Response,session,url_for
import config
from config_class import *
from datetime import timedelta
from _md5 import MD5Type
import hashlib
from controllor.usercontroller import usercontroller
from controllor.jobcontroller import jobcontroller

app = Flask(__name__)
app.config['DEBUG']=True
app.config['PERMANENT_SESSION_LIFETIME']=timedelta(minutes=30)
#使用class定义配置
app.config.from_object(DebugConfig)
# 使用config 文件定义配置
app.config.from_object(config)

app.register_blueprint(usercontroller)
#绑定路由
app.register_blueprint(jobcontroller)

@app.route('/')  #URL路由
def index():
    return render_template('index.html')

if __name__ == '__main__':
    app.run(host=app.config['SERVER_ADDR'],port=app.config['SERVER_PORT'],debug=True)

#controller文件夹下-jobcontroller.py实现代码
from flask import Blueprint,Flask,render_template,request,Response,session,url_for,jsonify
from service.jobservice import JobService
from entity.job import Job
import json

jobService=JobService()  #引入服务层

jobcontroller=Blueprint('jobcontroller',__name__)

@jobcontroller.route('/goajaxjob.do',methods=['POST','GET'])
def goAjaxJob():
    return render_template('systeminfo/jobajax.html')
    pass

@jobcontroller.route('/ajaxjob.do',methods=['POST','GET'])
def getJobInfo():
    jobData = request.get_data()
    jobDict = json.loads(jobData)
    tData = {}

    job=Job()
    jobId=int(jobDict.get('jobId'))
    job.jobId=jobId
    job.jobPosition=jobDict.get('jobPosition')
    job.jobCompany=jobDict.get('jobCompany')
    job.jobSalary=jobDict.get('jobSalary')
    job.jobCity=jobDict.get('jobCity')

    currentPage = int(jobDict.get('currentPage'))
    pageSize = int(jobDict.get('pageSize'))
    opr = jobDict.get('opr')

    delResult = 0
    if opr == 'del':
        delResult = jobService.removeJob(jobId)
        pass
    elif opr == 'update':
        tJob = jobService.findJobByJobId(jobId)
        tData['jobId'] = tJob.jobId
        tData['jobPosition'] = tJob.jobPosition
        tData['jobCompany'] = tJob.jobCompany
        tData['jobSalary'] = tJob.jobSalary
        tData['jobCity'] = tJob.jobCity
        returnData = {'code': 1, 'jobData': tData, 'pageSize': pageSize, 'currentPage': currentPage, 'opr': 'update'}
        return json.dumps(returnData)
    elif opr == 'submitUpdate':
        jobService.updateJob(job)
    elif opr=='submitadd':
        jobService.addJob(job,pageSize, currentPage)


    result = jobService.findPageJobList(job, pageSize, currentPage)
    counts = jobService.countJobs(job)
    totalPage = 0

    if (counts % pageSize == 0):
        totalPage = counts // pageSize
    else:
        totalPage = counts // pageSize + 1
        pass

    returnData = {'code': 1, 'jobData': result, 'pageSize': pageSize, 'currentPage': currentPage,
                  'totalPage': totalPage, 'delcode': delResult, 'opr': 'search', 'counts': counts}

    return json.dumps(returnData)
    pass


#service文件夹下-jobservice.py实现代码
from dao.jobdao import JobDao
from entity.job import Job

class JobService():

    def findPageJobList(self,job,pageSize,currentPage):
        jobDao=JobDao()
        return jobDao.findPageJobList(job,pageSize,currentPage)
        pass

    def removeJob(self,jobId):
        jobDao=JobDao()
        return jobDao.removeJob(jobId)
        pass

    def updateJob(self,job):
        jobDao=JobDao()
        return jobDao.updateJob(job)
        pass

    def addJob(self,job,pageSize,currentPage):
        jobDao = JobDao()
        return jobDao.addJob(job)
        pass

    def countJobs(self,job):
        jobDao = JobDao()
        return jobDao.countJobs(job)[0]
        pass

    def findJobByJobId(self,jobId):
        jobDao=JobDao()
        result=jobDao.findJobByJobId(jobId)
        job=None
        if result:
            job=Job()
            job.jobId=result[0][0]
            job.jobPosition=result[0][1]
            job.jobCompany=result[0][2]
            job.jobSalary=result[0][4]
            job.jobCity=result[0][12]
            pass
        return job
        pass
    pass

#dao层文件夹-jobdao.py代码实现
from .basedao import BaseDao
class JobDao(BaseDao):
    def findPageJobList(self,job,pageSize,currentPage):
        try:
            params=[]
            #sql语句和parms就需要是动态
            sql = "select * from job_position where 1=1 "  #where 1=1是为了便于增加and
            if job.jobPosition:
                sql+=" and job_position like %s "   #模糊查询
                params.append('%'+job.jobPosition+'%')
                pass
            if job.jobCompany:
                sql+=" and job_company like %s "   #模糊查询
                params.append('%'+job.jobCompany+'%')
                pass
            if job.jobCity:
                sql+="and job_city=%s "
                params.append(job.jobCity)
                pass
            if job.jobSalary:
                sql += " and job_salary like %s "  # 模糊查询
                params.append('%' + job.jobSalary + '%')
                pass

            startRow=(currentPage-1)*pageSize
            sql+="limit %s,%s "
            params.append(startRow)
            params.append(pageSize)

            self.getConnection()
            self.execute(sql,params)
            result = self.fetch()
        finally:
            self.close()
        return result
        pass

    def countJobs(self,job):
        params = []
        # sql语句和parms就需要是动态
        sql = "select count(*) from job_position where 1=1 "  # where 1=1是为了便于增加and
        if job.jobPosition:
            sql += " and job_position like %s "  # 模糊查询
            params.append('%' + job.jobPosition + '%')
            pass
        if job.jobCompany:
            sql += " and job_company like %s "  # 模糊查询
            params.append('%' + job.jobCompany + '%')
            pass
        if job.jobCity:
            sql += "and job_city=%s "
            params.append(job.jobCity)
            pass
        if job.jobSalary:
            sql += " and job_salary like %s "  # 模糊查询
            params.append('%' + job.jobSalary + '%')
            pass
        self.getConnection()
        self.execute(sql, params)
        result = self.fetchOne()
        return result
        pass

    def removeJob(self, jobId):
        try:
            sql = "delete from job_position where job_id=%s"
            self.getConnection()
            result = self.execute(sql, (jobId,))
            self.commit()
            return result
        finally:
            self.close()
        pass

    def updateJob(self, job):
        try:
            sql = "update job_position set job_position=%s,job_company=%s,job_salary=%s,job_city=%s where job_id=%s"
            self.getConnection()
            result = self.execute(sql, (job.jobPosition,job.jobCompany,job.jobSalary,job.jobCity,job.jobId))
            self.commit()
            return result
        finally:
            self.close()
        pass

    def addJob(self,job):
        try:
            sql = "insert into job_position(job_position,job_company,job_salary,job_city) values (%s,%s,%s,%s)"
            self.getConnection()
            result=self.execute(sql, (job.jobPosition,job.jobCompany,job.jobSalary,job.jobCity))
            self.commit()  #执行了sql语句之后要commit
            return result
        finally:
            self.close()
        pass

    def findJobByJobId(self,jobId):
        try:
            sql="select * from job_position where job_id=%s"
            self.getConnection()
            self.execute(sql,(jobId,))
            result=self.fetch()
        finally:
            self.close()
        return result
    pass

#entity层job.py代码实现
class Job():
    def __init__(self):
        self.__jobId = None
        self.__jobPosition = None
        self.__jobCompany = None
        self.__jobCity = None
        self.__jobSalary = None
        pass

    @property
    def jobId(self):
        return self.__jobId
        pass

    @jobId.setter
    def jobId(self, jobId):
        self.__jobId = jobId
        pass

    @property
    def jobPosition(self):
        return self.__jobPosition
        pass

    @jobPosition.setter
    def jobPosition(self, jobPosition):
        self.__jobPosition = jobPosition
        pass

    @property
    def jobCompany(self):
        return self.__jobCompany
        pass

    @jobCompany.setter
    def jobCompany(self, jobCompany):
        self.__jobCompany = jobCompany
        pass

    @property
    def jobCity(self):
        return self.__jobCity
        pass

    @jobCity.setter
    def jobCity(self, jobCity):
        self.__jobCity = jobCity
        pass

    @property
    def jobSalary(self):
        return self.__jobSalary
        pass

    @jobSalary.setter
    def jobSalary(self, jobSalary):
        self.__jobSalary = jobSalary
        pass

    pass


//jobajaxdata.js代码实现
function getJobData(currentPage, pageSize, opr, jobId) {

    jobPosition =  document.searchForm.jobPosition.value
    jobCompany=document.searchForm.jobCompany.value
    jobCity=document.searchForm.jobCity.value
    jobSalary = document.searchForm.jobSalary.value

    if(opr == 'del'){
        if(!confirm('确定要删除吗?')){
            return false
        }
    }else if(opr == 'submitUpdate'){
        jobPosition =  document.jobForm.jobPosition.value
        jobCompany=document.jobForm.jobCompany.value
        jobCity=document.jobForm.jobCity.value
        jobSalary = document.jobForm.jobSalary.value
        jobId = document.jobForm.jobId.value
        currentPage = document.jobForm.currentPage.value
        pageSize = document.jobForm.pageSize.value
    }else if(opr=='search1'){
        jobPosition=null
        jobCompany=null
        jobCity=null
        jobSalary=null
    }else if(opr=='add'){
        $('#modal-default1').modal()
        return false
    }else if(opr=='submitadd'){
        jobPosition =  document.jobaddForm.jobPosition.value
        jobCompany=document.jobaddForm.jobCompany.value
        jobCity=document.jobaddForm.jobCity.value
        jobSalary = document.jobaddForm.jobSalary.value
        currentPage = document.jobaddForm.currentPage.value
        pageSize = document.jobaddForm.pageSize.value
    }

    $.ajax({
        type: 'post',                            // 传数据的方式
        url: '/ajaxjob.do',
        dataType: 'json',                        // xml、json、script、html
        data:JSON.stringify({
            'jobId': jobId,     //  $('#userName') == document.getElementById('userName')
            'jobPosition':jobPosition,
            'jobCompany':jobCompany,
            'jobSalary':jobSalary,
            'jobCity':jobCity,
            'pageSize': pageSize,
            'currentPage': currentPage,
            'opr': opr
        }),
        error: function(xhr, err){
            alert('请求失败,请检查,' + err + '!')
        },
        success: function(data, textStatus){    // success对应的回调函数的第一个参数,是服务器返回的数据
            if(data.code == 1 && opr != 'update' && opr !='add'){
                var htmlText = ""
                for(var i =0;i <data.jobData.length;i++){
                    htmlText += '<tr>' +
                        '            <td align="center"><input type="checkbox" name="jobId" value="'+  data.jobData[i][0] +'" /></td>\n' +
                        '            <td class="text-blue">' + data.jobData[i][0] + '</td>\n' +
                        '            <td class="text-aqua">' + data.jobData[i][1] + '</td>\n' +
                        '            <td class="text-purple">' + data.jobData[i][2] + '</td>\n' +
                        '            <td class="text-orange">' + data.jobData[i][12] + '</td>\n' +
                        '            <td class="text-success">' + data.jobData[i][4] + '</td>\n' +
                        '            <td>\n' +
                        ' <button type="button" class="btn btn-danger" οnclick="getJobData('+ data.currentPage +',' + data.pageSize + ','+ '\'del\''+',' + data.jobData[i][0] +')">删除</button>' +
                        ' <button type="button" class="btn btn-info" οnclick="getJobData('+ data.currentPage +',' + data.pageSize + ','+ '\'update\''+',' + data.jobData[i][0] +')">修改</button>'+
                        ' <button type="button" class="btn btn-success" οnclick="getJobData('+ data.currentPage +',' + data.pageSize + ','+ '\'add\''+',' + data.jobData[i][0] +')">添加</button>'+
                        '            </td>\n' +
                        '        </tr>\n'
                }
                pageText = '<tr><td colspan="5">'+ '当前第' + data.currentPage + '页&nbsp;&nbsp;总共有' + data.totalPage + '页&nbsp;&nbsp;';
                if(data.currentPage <= 1) {
                    pageText += '首页 &nbsp;&nbsp;上一页&nbsp;&nbsp;';
                }else{
                     pageText += '<a href="javascript:getJobData(1,10,\'search\', 0);">首页</a> &nbsp;&nbsp;' +
                        '<a href="javascript:getJobData(' + (data.currentPage - 1) + ', 10, \'search\', 0);">上一页</a>&nbsp;&nbsp;';
                }

                if(data.currentPage >= data.totalPage){
                     pageText += '下一页&nbsp;&nbsp;尾页&nbsp;&nbsp;';
                }else {
                    pageText += '<a href="javascript:getJobData(' + (data.currentPage + 1) + ', 10, \'search\', 0);">下一页</a>&nbsp;&nbsp;' +
                    '<a href="javascript:getJobData(' + data.totalPage + ', 10, \'search\', 0);">尾页</a>&nbsp;&nbsp;';
                }
                pageText +='总共有'+data.counts+'数据'+'</td></tr>'
                $('#dataBody').empty()
                $('#dataBody').append(htmlText)
                $('#dataBody').append(pageText)

                document.searchForm.currentPage.value = data.currentPage
                document.searchForm.pageSize.value=data.pageSize

            }else if(data.code == 1 && opr == 'update'){
                document.jobForm.jobPosition.value = data.jobData.jobPosition
                document.jobForm.jobCompany.value = data.jobData.jobCompany
                document.jobForm.jobSalary.value = data.jobData.jobSalary
                document.jobForm.jobCity.value = data.jobData.jobCity
                document.jobForm.jobId.value = data.jobData.jobId
                document.jobForm.currentPage.value = data.currentPage
                document.jobForm.pageSize.value = data.pageSize
                $('#modal-default').modal()
                //v$('#modal-default').
            }

        }
    });
}
$(document).ready(
    function(){
        getJobData(1, 10, 'search', 0)
    }
)

<!-- job实现页面-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>求职信息管理</title>
    <link rel="stylesheet" href="{{ url_for('static',filename='bootstrap/dist/css/bootstrap.min.css') }}"/>
    <!-- Font Awesome -->
    <link rel="stylesheet" href="{{ url_for('static',filename='font-awesome/css/font-awesome.min.css') }}"/>
    <!-- Ionicons -->
    <link rel="stylesheet" href="{{ url_for('static',filename='bower_components/Ionicons/css/ionicons.min.css') }}"/>
    <!-- Theme style -->
    <link rel="stylesheet"  href="{{ url_for('static',filename='css/AdminLTE.css') }}" />
    <link rel="stylesheet"  href="{{ url_for('static',filename='css/style.css') }}" />
    <script type="text/javascript" src="{{ url_for('static',filename='js/jquery-3.2.1.min.js') }}"></script>
    <script type="text/javascript" src="{{ url_for('static',filename='js/formvalidator.js') }}"></script>
    <!-- Bootstrap 3.3.7 -->
    <script src="{{ url_for('static', filename='bootstrap/dist/js/bootstrap.min.js') }}"></script>
    <script type="text/javascript" src="{{ url_for('static',filename='js/jobdata.js') }}"></script>
</head>
<body>
<div id="searchBox">
    <form method="post" name="searchForm">
        所需职业名称:<input type="text" name="jobPosition" />
        公司名称:  <input type="text" name="jobCompany" />
        所在城市:  <input type="text" name="jobCity" />
        可得薪水:  <input type="text" name="jobSalary" />
                <input type="hidden" name="currentPage" value="1"/>
                <input type="hidden" name="pageSize" value="10"/>
                <input type="button" class="btn-warning" value="查询" onclick="getJobData(1, 10, 'search', 0)">
                <input type="button" class="btn-primary" value="所有信息" onclick="getJobData(1, 10, 'search1', 0)">
    </form>
    <table class="table table-responsive table-bordered">
        <caption>{{ message }}</caption>
        <thead>
            <tr>
                <th align="center">
                    <input type="button" value="全选"/>
                    <input type="button" value="反选"/>
                </th>
                 <th>就职信息ID</th>
                 <th>所需职业名称</th>
                 <th>公司名称</th>
                 <th>所在城市</th>
                 <th>可得薪水</th>
                 <th>操作</th>
            </tr>
        </thead>
        <tbody id="dataBody">
        </tbody>
    </table>
    <div class="modal fade" id="modal-default">
          <div class="modal-dialog">
            <div class="modal-content">
              <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                  <span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">修改就职相关信息</h4>
              </div>
              <div class="modal-body">
                     <form method="post" name="jobForm">
                         所需职业名称:<input type="text" name="jobPosition" /><br>
                         公司名称:  <input type="text" name="jobCompany" /><br>
                         所在城市:<input type="text" name="jobCity" /><br>
                         可得薪水:  <input type="text" name="jobSalary" />
                        <input type="hidden" name="jobId"/>
                        <input type="hidden" name="currentPage" value="1"/>
                        <input type="hidden" name="pageSize" value="10"/>
                    </form>
              </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-default pull-left" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="getJobData(1, 10, 'submitUpdate', 0)">保存</button>
              </div>
            </div>
            <!-- /.modal-content -->
          </div>
          <!-- /.modal-dialog -->
        </div>
    </div>

<div class="modal fade" id="modal-default1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">添加相关信息</h4>
            </div>
            <div class="modal-body">
                <form method="post" name="jobaddForm">

                    所需职业名称:<input type="text" name="jobPosition"/><br>
                    公司名称: <input type="text" name="jobCompany"/><br>
                    所在城市:<input type="text" name="jobCity"/><br>
                    可得薪水: <input type="text" name="jobSalary"/>
                    <input type="hidden" name="jobId"/>
                    <input type="hidden" name="currentPage" value="1"/>
                    <input type="hidden" name="pageSize" value="10"/>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default pull-left" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="getJobData(1, 10, 'submitadd', 0)">保存</button>
            </div>
        </div>
        <!-- /.modal-content -->
    </div>
    <!-- /.modal-dialog -->
</div>


</body>
</html>

以下为实现效果

python-Flask框架用ajax对数据表实现简单的增删改查