Python Web 实现Ajax调用

来源:互联网 发布:淘宝评价心怎么升级 编辑:程序博客网 时间:2024/06/05 21:49

Html前端:

$.ajax({                    type:"GET",                    url:'/getmobile',                    data:'id='+id,                    dataType:"json",                    success:function(data){                       alert(data);                    },                    error:function(XMLHttpRequest, textStatus, errorThrown) {                alert(XMLHttpRequest.status);                alert(XMLHttpRequest.readyState);                alert(textStatus);               }      });

Python后端:

class  GetMobileHandler(web.RequestHandler):    def get(self):        id = self.get_argument('id')        print id        finishedsts = mongodb.t_ecg_report.find({'apply.status' : { '$gte': '3' }}).count()        doctornum= self.application.db.execute_rowcount("SELECT  *  FROM t_p_user  where category in ('0','3')")        hosnum= self.application.db.execute_rowcount("SELECT * from t_p_institution where category='0'")        self.write('''{"finishedsts":"'''+str(finishedsts+40000)+'''","doctornum":"'''+str(doctornum+100)+'''","hosnum":"'''+str(hosnum+100)+'''"}''')

上面类绑定了"/getmobile",

注意以下几点:

1.html设置参考标准的ajax设置,后台Python其实就是捕获一个不同的get请求,ajax如果请求类型是get则入参是将data中变量转成参数拼接在URL中,比如上述python接受到的请求就是:/getmobile?id=XXXXX


2.ajax如何调用python的接口,实际上ajax调用的是一个普通的http请求,python也是接受一个普通http请求。

所以如果ajax调用报错,比如返回 500 ,400,403之类的,可以先用HttpRequester之类的模拟请求调用

如果成功则再试ajax,如果不成功那是python接口本身的问题。

0 0
原创粉丝点击