将JSON与AJAX和Python数据库结合使用

Using JSON with AJAX and Python database

本文关键字:数据库 结合 Python JSON AJAX      更新时间:2023-09-26

我是python的新手,正在尝试通过python访问数据库,并使用AJAX在JSON数组中返回一些结果
我通过返回一个JSON列表并使用js提醒它来测试它。当我不使用db连接时,它可以工作,但一旦我添加它,js警报也会停止。当我运行文件CCD_ 1时,db连接似乎工作正常。数据库连接在一个单独的文件webairdb.py
中有人能帮我找出问题吗?

getSchedule.py

#!D:/Programming/Software/python3.4.4/python
import sys, json,cgi, cgitb, mysql.connector, webairdb
cgitb.enable()
fs = cgi.FieldStorage()
sys.stdout.write("Content-Type: application/json")
sys.stdout.write("'n")
sys.stdout.write("'n")
conn = webairdb.getConnection()
conn.close()
listr = [11111]
sys.stdout.write(json.dumps(listr))
sys.stdout.write("'n")
sys.stdout.close()

webairdb.py

#!D:/Programming/Software/python3.4.4/python
import cgi, cgitb, imp, mysql.connector
host ="localhost"
db = "webair"
user = "root"
password = ""
def getConnection():
    conn =   mysql.connector.connect(user=user,password=password,host=host,database=db)
    if conn.is_connected():
        print("aaaqqqq")
    return conn

webairdb.py中,您向sys.stdout写入(print就是这样做的(-有效地破坏了json输出。(您可能想在浏览器中按F12查看输出(

因此,只需删除它,然后写入sys.stderr或使用日志记录即可。

您还应该考虑使用wsgi而不是cgi,这会让事情变得更容易(根本不需要关心打印(,或者使用像bottle或cherrypy这样的框架。