web 框架2 tornado ajax cookie 不用每次重启tornado 配置自动刷新网页就能重读

Tornado

 

Tornado 是 FriendFeed 使用的可扩展的非阻塞式 web 服务器及其相关工具的开源版本。这个 Web 框架看起来有些像web.py 或者 Google 的 webapp,不过为了能有效利用非阻塞式服务器环境,这个 Web 框架还包含了一些相关的有用工具 和优化。

Tornado 和现在的主流 Web 服务器框架(包括大多数 Python 的框架)有着明显的区别:它是非阻塞式服务器,而且速度相当快。得利于其 非阻塞的方式和对 epoll 的运用,Tornado 每秒可以处理数以千计的连接,这意味着对于实时 Web 服务来说,Tornado 是一个理想的 Web 框架。我们开发这个 Web 服务器的主要目的就是为了处理 FriendFeed 的实时功能 ——在 FriendFeed 的应用里每一个活动用户都会保持着一个服务器连接。(关于如何扩容 服务器,以处理数以千计的客户端的连接的问题,请参阅 C10K problem。)

 

pip install tornado
源码安装
    https://pypi.python.org/packages/source/t/tornado/tornado-4.3.tar.gz

 

简单介绍 

#!/usr/bin/env python
# _*_ coding:utf-8 _*_
__author__ = 'liujianzuo'

import tornado.ioloop
import tornado.web

import uimodule as md  #当前文件所在目录的脚本
import uimethod as mt

INPUTS_LIST = [ ]
class MainHandler(tornado.web.RequestHandler):
    def get(self):
        # self.write("hello world")
        # self.render("s1.html")
       
        name = self.get_argument('xxx', None)
        if name:
            INPUTS_LIST.append(name)
         # xxxooo = INPUTS_LIST  #  这样不行传入报错
        self.render("s1.html", npm="NPM888",xxxooo=INPUTS_LIST) #不能只写一个列表名称,要把前端用到的变量也定义上
    def post(self, *args, **kwargs):
        # self.write("hello world")
        name = self.get_argument('xxx',None)
        INPUTS_LIST.append(name)
        # xxxooo=INPUTS_LIST 这样不行传入报错
        self.redirect("s1.html",xxxooo=INPUTS_LIST)  # 跳转到某个页面,url也换

class Xx(tornado.web.RequestHandler):
    def get(self):
        self.render("77.html")



settings = {
    "template_path":"tpl" , #  模板路径的配置
    "static_path": "static",
    # "static_url_prefix": "/sss/",  # 有这个的话,前端就要写成 引用/sss/xxx.css了
    "ui_methods":mt,
    "ui_modules": md,
}


#路由映射,路由系统

application = tornado.web.Application([
    (r"/index",MainHandler),
    (r"/$",Xx),
],**settings)


if __name__ == '__main__':
    # socket 运行起来

    application.listen(8898)
    tornado.ioloop.IOLoop.instance().start()    

  

<link type="text/css" rel="stylesheet" href="static/mycss.css">

  index。html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>1</title>
    <link type="text/css" rel="stylesheet" href="static/mycss.css">
</head>
<body>

<div>hello jjjjjjj</div>

<div>提交内容</div>
<form method="post" action="/index">
    <input type="text" name="xxx">
    <input type="submit" value="提交">
</form>

<h2>显示内容</h2>
<h3>{{ npm }}</h3>
<h3>{{ func(npm) }}</h3>
<h3>{% module custom() %}</h3>


<ul>
    {% for item in xxxooo %}
        {% if item == "alex" %}
            <li style="color:red">{{ item }}</li>
        {% else %}
            <li>{{item}}</li>
        {% end %}
    {% end %}
</ul>


</body>
</html>
index.html

 

但是 上面的link css可以用后面要讲的 {{static_url(文件名)}} 效果如下,可以利用缓存

<link rel="stylesheet" href='{{static_url("css/commons.css") }}' />
    <link rel="stylesheet" href='{{static_url("plugins/bootstrap3/css/bootstrap.css") }}' />

 

  

一、快速上手

 

#!/usr/bin/env python
# -*- coding:utf-8 -*-
  
import tornado.ioloop
import tornado.web
  
  
class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("Hello, world")
  
application = tornado.web.Application([
    (r"/index", MainHandler),
])
  
  
if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

第一步:执行脚本,监听 8888 端口

第二步:浏览器客户端访问 /index  -->  http://127.0.0.1:8888/index

第三步:服务器接受请求,并交由对应的类处理该请求

第四步:类接受到请求之后,根据请求方式(post / get / delete ...)的不同调用并执行相应的方法

第五步:方法返回值的字符串内容发送浏览器

 

插入点: 不用每次重启tornado 配置自动刷新网页就能重读

#!/usr/bin/env python
# -*- coding:utf-8 -*-


import Mapper
import tornado.ioloop
import tornado.web
from Web.Controllers.home import home

settings = {
    'template_path': 'Web/Views',
    'static_path': 'Web/statics',
    'static_url_prefix': '/statics/',
    'autoreload': True,
}

application = tornado.web.Application([
    (r"/index", home.IndexHandler),
], **settings)


if __name__ == "__main__":
    Mapper.static_mapper()
    application.listen(8888)
    instance = tornado.ioloop.IOLoop.instance()
    tornado.autoreload.start(instance)
    instance.start()
    # tornado.ioloop.IOLoop.instance().start()

  

 

暂时未说

#!/usr/bin/env python
# -*- coding:utf-8 -*-
#!/usr/bin/env python
# -*- coding:utf-8 -*-

import tornado.ioloop
import tornado.web
from tornado import httpclient
from tornado.web import asynchronous
from tornado import gen

import uimodules as md
import uimethods as mt

class MainHandler(tornado.web.RequestHandler):
        @asynchronous
        @gen.coroutine
        def get(self):
            print 'start get '
            http = httpclient.AsyncHTTPClient()
            http.fetch("http://127.0.0.1:8008/post/", self.callback)
            self.write('end')

        def callback(self, response):
            print response.body

settings = {
    'template_path': 'template',
    'static_path': 'static',
    'static_url_prefix': '/static/',
    'ui_methods': mt,
    'ui_modules': md,
}

application = tornado.web.Application([
    (r"/index", MainHandler),
], **settings)


if __name__ == "__main__":
    application.listen(8009)
    tornado.ioloop.IOLoop.instance().start()
异步非阻塞实例

 

二、路由系统

路由系统其实就是 url 和 类 的对应关系,这里不同于其他框架,其他很多框架均是 url 对应 函数,Tornado中每个url对应的是一个类。

#!/usr/bin/env python
# -*- coding:utf-8 -*-
  
import tornado.ioloop
import tornado.web
  
  
class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("Hello, world")
  
class StoryHandler(tornado.web.RequestHandler):
    def get(self, story_id):
        self.write("You requested the story " + story_id)
  
class BuyHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("buy.wupeiqi.com/index")
  
application = tornado.web.Application([
    (r"/index", MainHandler),
    (r"/story/([0-9]+)", StoryHandler),
])
  
application.add_handlers('buy.wupeiqi.com$', [
    (r'/index',BuyHandler),
])
  
if __name__ == "__main__":
    application.listen(80)
    tornado.ioloop.IOLoop.instance().start()

三、模板

Tornao中的模板语言和django中类似,模板引擎将模板文件载入内存,然后将数据嵌入其中,最终获取到一个完整的字符串,再将字符串返回给请求者。

Tornado 的模板支持“控制语句”和“表达语句”,控制语句是使用 {% 和 %} 包起来的 例如 {% if len(items) > 2 %}。表达语句是使用 {{ 和 }} 包起来的,例如 {{ items[0] }}

控制语句和对应的 Python 语句的格式基本完全相同。我们支持 ifforwhile 和 try,这些语句逻辑结束的位置需要用 {% end %} 做标记。还通过 extends 和 block 语句实现了模板继承。这些在 template 模块 的代码文档中有着详细的描述。

 

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title>老男孩</title>
    <link href="{{static_url("css/common.css")}}" rel="stylesheet" />
    {% block CSS %}{% end %}
</head>
<body>

    <div class="pg-header">

    </div>
    
    {% block RenderBody %}{% end %}
   
    <script src="{{static_url("js/jquery-1.8.2.min.js")}}"></script>
    
    {% block JavaScript %}{% end %}
</body>
</html>
layout.html
{% extends 'layout.html'%}
{% block CSS %}
    <link href="{{static_url("css/index.css")}}" rel="stylesheet" />
{% end %}

{% block RenderBody %}
    <h1>Index</h1>

    <ul>
    {%  for item in li %}
        <li>{{item}}</li>
    {% end %}
    </ul>

{% end %}

{% block JavaScript %}
    
{% end %}
index.html

 

模板语言的本质

字符串拼接后做的 exec 或compile

#!/usr/bin/env python
# -*- coding:utf-8 -*-


namespace = {'name':'wupeiqi','data':[18,73,84],}

code =  '''def hellocute():return  "name %s ,age %d" %(name,data[0],) '''

func = compile(code, '<string>', "exec")

exec(func,namespace)

result = namespace['hellocute']()

print(result)
模板语言本质 字符串拼接 并编译

test

#!/usr/bin/env python
# -*- coding:utf-8 -*-
  
import tornado.ioloop
import tornado.web
  
  
class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.render('home/index.html')
  
settings = {
    'template_path': 'template',
}
  
application = tornado.web.Application([
    (r"/index", MainHandler),
], **settings)
  
  
if __name__ == "__main__":
    application.listen(80)
    tornado.ioloop.IOLoop.instance().start()

  

在模板中默认提供了一些函数、字段、类以供模板使用:

  • escapetornado.escape.xhtml_escape 的別名
  • xhtml_escapetornado.escape.xhtml_escape 的別名
  • url_escapetornado.escape.url_escape 的別名
  • json_encodetornado.escape.json_encode 的別名
  • squeezetornado.escape.squeeze 的別名
  • linkifytornado.escape.linkify 的別名
  • datetime: Python 的 datetime 模组
  • handler: 当前的 RequestHandler 对象
  • requesthandler.request 的別名
  • current_userhandler.current_user 的別名
  • localehandler.locale 的別名
  • _handler.locale.translate 的別名
  • static_url: for handler.static_url 的別名
  • xsrf_form_htmlhandler.xsrf_form_html 的別名

Tornado默认提供的这些功能其实本质上就是 UIMethod 和 UIModule,我们也可以自定义从而实现类似于Django的simple_tag的功能:

自定义 方法模块 供前端使用

======武sir

1、定义

# uimethods.py
 
def tab(self):
    return 'UIMethod'
uimethods.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from tornado.web import UIModule
from tornado import escape

class custom(UIModule):

    def render(self, *args, **kwargs):
        return escape.xhtml_escape('<h1>wupeiqi</h1>')
        #return escape.xhtml_escape('<h1>wupeiqi</h1>')
uimodules.py

2、注册

#!/usr/bin/env python
# -*- coding:utf-8 -*-
#!/usr/bin/env python
# -*- coding:utf-8 -*-

import tornado.ioloop
import tornado.web
from tornado.escape import linkify
import uimodules as md
import uimethods as mt

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.render('index.html')

settings = {
    'template_path': 'template',
    'static_path': 'static',
    'static_url_prefix': '/static/',
    'ui_methods': mt,
    'ui_modules': md,
}

application = tornado.web.Application([
    (r"/index", MainHandler),
], **settings)


if __name__ == "__main__":
    application.listen(8009)
    tornado.ioloop.IOLoop.instance().start()
main.py

3、使用

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <link href="{{static_url("commons.css")}}" rel="stylesheet" />
</head>
<body>
    <h1>hello</h1>
    {% module custom(123) %}
    {{ tab() }}
</body>
index.html

 

 

=======end 武sir

 

========我的练习

1、定义 

   staic的文件  : css image js 是为下面的index。html服务的。。。不用考了。 而plugins 是bootstrap3 也是index.html用的这里主要用s1.html

 

#!/usr/bin/env python
# -*- coding:utf-8 -*-

def func(self,arg):

    return arg.lower()
uimethod.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-

from tornado.web import UIModule
from tornado import escape

class custom(UIModule):

    def render(self, *args, **kwargs):
        return "1234"
uimodule.py

2、注册

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import tornado.ioloop
import tornado.web
import uimethod as mt
import uimodule as md


INPUTS_LIST = []
USER_INFO = {'is_login': None}
NEWS_LIST = [
    {"title": '索宁被锁住了', "content": "好期待呀..."},
    {"title": '索宁真的被锁住了', "content": "太爽了..."}
]

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        # self.write("Hello, world")
        # 1、打开s1.html文件,读取内容(包含特殊语法)
        # 2、xxxooo = [11,22,33,44] && 读取内容(包含特殊语法)
        # 3、得到新的字符串
        # 4、返回给用户
        name = self.get_argument('xxx',None)
        if name:
            INPUTS_LIST.append(name)
        self.render("s1.html", npm="NPM888", xxxooo= INPUTS_LIST )
    # def post(self, *args, **kwargs):
    #     name = self.get_argument('xxx')
    #     INPUTS_LIST.append(name)
    #     self.render("s1.html",  xxxooo= INPUTS_LIST)


class IndexHandler(tornado.web.RequestHandler):

    def get(self, *args, **kwargs):
        self.render('index.html',user_info = USER_INFO, new_list=NEWS_LIST)

class LoginHandler(tornado.web.RequestHandler):

    def post(self, *args, **kwargs):
        username = self.get_argument('username',None)
        pwd = self.get_argument('pwd',None)
        if username == 'alex' and pwd == "123":
            USER_INFO['is_login'] = True
            USER_INFO['username'] = username
        else:
            USER_INFO['is_login'] = False
            USER_INFO['username'] = "登陆"
        self.redirect('index.html',user_info = USER_INFO,new_list=NEWS_LIST)
class PublishHandler(tornado.web.RequestHandler):

    def post(self, *args, **kwargs):
        title = self.get_argument('title',None)
        content = self.get_argument('content',None)
        temp = {'title':title, "content": content}
        NEWS_LIST.append(temp)
        # self.render('index.html',user_info = USER_INFO)
        self.redirect('/index')
settings = {
    'template_path': 'tpl', # 模板路径的配置
    'static_path': 'static',
    'static_url_prefix': '/sss/',
    'ui_methods': mt,
    'ui_modules': md,
}


# 路由映射,路由系统
application = tornado.web.Application([
    # (r"/index", MainHandler),
    (r"/index", IndexHandler),
    (r"/login", LoginHandler),
    (r"/publish", PublishHandler),
], **settings)


if __name__ == "__main__":
    # socket运行起来
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()
index.py

3、html 前端使用

    <h3>{{npm}}</h3>
    <h3>{{ func(npm) }}</h3>    直接是函数名 处理后端py 传过来的数据npm
    <h3>{% module  custom() %}</h3>   module 接 类名
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href='{{ static_url("commons.css") }}'/>
</head>
<body>
    <h1>提交内容:</h1>
    <form method="get" action="/index">
        <input type="text" name="xxx" />
        <input type="submit" value="提交" />
    </form>
    <h1>展示内容:</h1>
    <h3>{{npm}}</h3>
    <h3>{{ func(npm) }}</h3>
    <h3>{% module  custom() %}</h3>
    <ul>
        {% for item in xxxooo %}
            {% if item == "alex" %}
                <li style="color: red">{{item}}</li>
            {% else %}
                <li>{{item}}</li>
            {% end %}

        {% end %}
    </ul>

    <script src='{{ static_url("oldboy.js") }}'></script>
</body>
</html>
s1.html
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>抽屉新热榜</title>
    <link rel="stylesheet" href='{{static_url("css/commons.css") }}' />
    <link rel="stylesheet" href='{{static_url("plugins/bootstrap3/css/bootstrap.css") }}' />

</head>
<body>
<div class="pg-header">
    <div class="w">
        <a class="logo" href="/"></a>
        <div class="act-menu">
            <a href="/all/hot/recent/1" class="tb active">全部</a>
            <a href="/all/hot/recent/1" class="tb">42区</a>
            <a href="/all/hot/recent/1" class="tb">段子</a>
            <a href="/all/hot/recent/1" class="tb">图片</a>
            <a href="/all/hot/recent/1" class="tb">挨踢1024</a>
            <a href="/all/hot/recent/1" class="tb">你问我答</a>
        </div>
        <div class="key-sera">

            <form action="/search/show" method="post" name="searchFrm2" id="searchFrm2">
                <input type="text" class="search-txt-s" name="words" id="txtSearch2" autocomplete="off">

                <a href="javascript:;" class="i" name="searchBtn_2" id="searchBtn_3"><span class="ico"></span></a>
                <input type="hidden" value="1" id="page" name="page">
            </form>

        </div>

        <div class="action-nav">
            <a href="/show/flow/1" style="float:left;position:relative;" id="btnDtaiShw">动态
                <b class="notice-num-title" id="Dtai-num-title" style="right: 3px; display: none;">
                    <em id="Dtai-em"></em>
                </b>
            </a>
            <a href="javascript:;" id="btnNotShw" class="notice-box">通知
                <b class="notice-num-title" id="notice-num-title" style="display: none;">
                    <em id="notice-em"></em>
                    <i>+</i>
                </b>
            </a>
            {% if user_info["is_login"] %}
                <a href="/user/link/saved/1" id="loginUserNc" class="userPro-Box">
                    <img src="http://img2.chouti.com/CHOUTI_05B313F703D34646848BCC5571510683_W148H148=30x30).jpg" id="userProImg">
                    <span class="u-nick" id="userProNick">{{user_info["username"]}}</span>
                    <em id="userProArr"></em>
                </a>
            {% else %}
            <a onclick="Login();">登录</a>
            <a>注册</a>
            {% end %}
        </div>
        <div class="user-opr-box" id="userOprBox" style="left: 869px; display: none;">
            <a href="/user/link/saved/1" style="border-top:0;">我的新热榜</a>
            <a href="/profile">设置</a>
            <a class="logout" href="javascript:;">退出</a>
            <a href="http://www.chouti.com/cdu_45792645155" target="_blank" class="ie6-a">我的收藏</a>
        </div>
    </div>
</div>

<div class="pg-body">

    <div style="background-color: #eee;">
        <div class="w body-content">
            <div class="clearfix">
                <div class="content-l" >
                    <div class="nav-top-area">
                        <div class="child-nav">
                            <!-- 当不是全部页面时 -->
                            <a href="/r/pic/hot/1" hidefocus="false" class="icons active hotbtn" id="hotts-nav-btn">最热</a>
                            <a href="/r/pic/new/1" hidefocus="false" class="newbtn" id="newest-nav-btn">最新</a>
                            <!-- 当是全部页面时 -->
                        </div>
                        <!-- 当是全部页面时 -->
                        <a href="javascript:void(0);" onclick="Publish();" class="publish-btn" id="publishBtn" lang="pic">
                            <span class="ico n1"></span><span class="n2">发布</span>
                        </a>

                    </div>


                    <div class="content-list" id="content_list">
                        {% for new in new_list %}
                            <div class="item">

                                <div class="timeIntoPool">1458285240218000,1458288835879000</div>

                                <div class="news-pic">
                                    <img lang="8118680" original="http://img2.chouti.com/CHOUTI_18A9ECD30D9044D8872301BDC8FD4460_W265H265=C60x60.jpg" src="http://img2.chouti.com/CHOUTI_18A9ECD30D9044D8872301BDC8FD4460_W265H265=C60x60.jpg" alt="抽屉新热榜" style="display: inline;">
                                </div>

                                <div class="null-item"></div>

                                <div class="news-content" id="newsContent8118680">
                                    <div class="part1">
                                        <a href="http://wallstreetcn.com/node/232597" class="show-content" target="_blank" onmousedown="linksClickStat(8118680);">{{new['title']}}</a>
                                        <span class="content-source">-wallstreetcn.com</span>
                                        <!-- 段子和谣言类别不显示类别名称 -->
                                        <a href="/r/news/hot/1" class="n2"><span class="content-kind">42区</span></a>
                                        <!-- 来源手机客户端 -->
                                        <!-- 显示话题标签 -->
                                    </div>
                                    <!-- 显示摘要 -->
                                    <div class="area-summary">
                                        <span class="summary">{{new['content']}}</span>
                                    </div>
                                    <div class="part2" share-pic="http://img2.chouti.com/CHOUTI_AD764B84163A4A8093C2BF54CEAA4AAB_W400H266.jpg" share-title="进入调整期?深圳二手房成交较年初锐减30%" share-summary="多家中介数据显示,深圳3月二手房成交量比1月下降超过30%,新房成交量同样出现下降。分析称,政策收紧预期较大程度上影响了市场成交,而业主方多看好后市,双方存在一定博弈。预计4月评估价调整政策落地后,二手房市场或进入短暂调整期。" share-linkid="8118680" share-subject="42区">
                                        <a href="javascript:;" class="digg-a" title="推荐"><span class="hand-icon icon-digg"></span><b>7</b><i style="display:none">8118680</i></a>
                                        <a href="javascript:;" class="discus-a" id="discus-a-8118680" lang="8118680" title=""><span class="hand-icon icon-discus"></span><b>4</b></a>
                                        <a href="javascript:;" class="collect-a" id="collect-a-8118680" lang="8118680" title="加入私藏" destjid="cdu_45792645155" jid="chouti150326"><span class="hand-icon icon-collect"></span><b>私藏</b></a>
                                        <a href="/user/chouti150326/submitted/1" class="user-a"><span><img src="http://img2.chouti.com/group11/M00/07/D0/wKgCPlUvbAWP7voYAAAZHLh58GA463=15x15.jpg"></span><b>wallstreetcn</b></a>
                                        <span class="left time-into"><a class="time-a" href="/link/8118680" target="_blank"><b>1小时18分钟前</b></a><i>入热榜</i></span>
                                        <!-- 分享各微博的按钮 -->

                                        <span class="share-site-to" style="visibility: hidden;"><i>分享到</i><span class="share-icon"><a class="icon-sina" id="icon-sina" title="分享到新浪微博" href="javascript:;" hidefocus="true"></a><a class="icon-douban" id="icon-douban" title="分享到豆瓣" href="javascript:;" hidefocus="true"></a><a class="icon-qqzone" id="icon-qqzone" title="分享到QQ空间" href="javascript:;" hidefocus="true"></a><a class="icon-tenxun" id="icon-tenxun" title="分享到腾讯微博" href="javascript:;" hidefocus="true"></a><a class="icon-renren" id="icon-renren" title="分享到人人网" href="javascript:;" hidefocus="true"></a><a class="share-none"> </a></span></span></div>

                                </div>

                            </div>
                        {% end %}



                    </div>
                </div>
                <div class="content-r">

                </div>
            </div>
        </div>
    </div>

</div>

<div class="modal fade" id="login" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
  <div class="modal-dialog" role="document">
    <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" id="exampleModalLabel">用户登录</h4>
      </div>
        <form action="/login" method="post">
        <div class="modal-body">

          <div class="form-group">
            <label class="control-label">用户名:</label>
            <input type="text" name="username" class="form-control" >
          </div>
          <div class="form-group">
            <label  class="control-label">密码:</label>
            <input type="password" name="pwd" class="form-control" >
          </div>


          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            <button type="submit" class="btn btn-primary">提交</button>
          </div>
        </form>
    </div>
  </div>
</div>
<div class="modal fade" id="pub" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
  <div class="modal-dialog" role="document">
    <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>
        <form action="/publish" method="post">
        <div class="modal-body">

          <div class="form-group">
            <label class="control-label">标题:</label>
            <input type="text" name="title" class="form-control" >
          </div>
          <div class="form-group">
              <label  class="control-label">内容:</label>
              <textarea class="form-control" name="content"></textarea>
          </div>


          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            <button type="submit" class="btn btn-primary">提交</button>
          </div>
        </form>
    </div>
  </div>
</div>

<script src='{{static_url("js/jquery-2.1.4.min.js") }}'></script>
<script src='{{static_url("plugins/bootstrap3/js/bootstrap.js") }}' ></script>
<script>
    $(function(){
        $('#loginUserNc,#userOprBox').mouseover(function(){
            $('#userOprBox').css('display', 'block');
            $('#loginUserNc').addClass('active');
        }).mouseout(function () {
            $('#userOprBox').css('display', 'none');
            $('#loginUserNc').removeClass('active');
        })
    });
    function Login() {
        $('#login').modal('show');
    }
    function Publish() {
        $('#pub').modal('show');
    }
</script>
</body>
</html>
index.html 其实在这用不着,只是这个是附带发布文章用的。。。那个案例一起搞过来了

 

四、实用功能 

 

1、静态文件

对于静态文件,可以配置静态文件的目录和前段使用时的前缀,并且Tornaodo还支持静态文件缓存。

#!/usr/bin/env python
# -*- coding:utf-8 -*-
 
import tornado.ioloop
import tornado.web
 
 
class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.render('home/index.html')
 
settings = {
    'template_path': 'template',
    'static_path': 'static',
    'static_url_prefix': '/static/',
}
 
application = tornado.web.Application([
    (r"/index", MainHandler),
], **settings)
 
 
if __name__ == "__main__":
    application.listen(80)
    tornado.ioloop.IOLoop.instance().start()
main.py
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <link href="{{static_url("commons.css")}}" rel="stylesheet" />
</head>
<body>
    <h1>hello</h1>
</body>
</html>
index.html

备注:静态文件缓存的实现

def get_content_version(cls, abspath):
        """Returns a version string for the resource at the given path.

        This class method may be overridden by subclasses.  The
        default implementation is a hash of the file's contents.

        .. versionadded:: 3.1
        """
        data = cls.get_content(abspath)
        hasher = hashlib.md5()
        if isinstance(data, bytes):
            hasher.update(data)
        else:
            for chunk in data:
                hasher.update(chunk)
        return hasher.hexdigest()
静态文件缓存源码

 

3、cookie

cookie是存在在浏览器,服务器端主动往浏览器端写入内容,是保存在浏览器的键值对

Tornado中可以对cookie进行操作,并且还可以对cookie进行签名以放置伪造。

a 我的cookie 案例

默认访问主页,不能访问后台,只能登陆成功才能访问后台,同cookie确定是否登陆

#!/usr/bin/env python
# _*_ coding:utf-8 _*_
__author__ = 'liujianzuo'

import  tornado.ioloop
import tornado.web

class IndexHandler(tornado.web.RequestHandler):

    def get(self, *args, **kwargs):
        self.render("index.html")

class ManagerHandler(tornado.web.RequestHandler):

    def get(self, *args, **kwargs):
        co = self.get_cookie("auth")
        if co == "1":
            self.render("manager.html")
        else:
            self.redirect("/index")

class LogoutHandler(tornado.web.RequestHandler):

    def get(self, *args, **kwargs):
        self.set_cookie("auth",'0')  # cookie的value必须是字符串
        self.redirect("/login")



class LoginHandler(tornado.web.RequestHandler):

    def get(self, *args, **kwargs):
        self.render("login.html",status_text="")

    def post(self, *args, **kwargs):
        username = self.get_argument("username",None)
        pwd = self.get_argument("password",None)

        if username == "alex" and pwd == "sb":
            self.set_cookie("auth", '1') # cookie的value必须是字符串
            self.redirect("/manager")

        else:
            self.render("login.html",status_text = "登陆失败")

settings = {
    "template_path" : "views",  # 模板路径的配置
}

#路由映射  路由系统

application = tornado.web.Application([
    (r"/index",IndexHandler),
    (r"/login",LoginHandler),
    (r"/logout",LogoutHandler),
    (r"/manager",ManagerHandler),

],**settings)


if __name__ == '__main__':
    # socket 运行起来

    application.listen(8880)
    tornado.ioloop.IOLoop.instance().start()
index.py
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>

    <h1>首页</h1>

</body>
</html>
index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登陆</title>
</head>
<body>
    <form method="post" action="/login">
        <input type="text" name="username">
        <input type="password" name="password">
        <input type="submit" value="登陆">
        <span style="color:red">{{status_text}}</span>
    </form>

</body>
</html>
login.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>后台管理</title>
</head>
<body>

<a href="/logout">退出</a>
<h1>银行卡余额</h1>
</body>
</html>
manager.html
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
__author__ = 'liujianzuo'

import  tornado.ioloop
import tornado.web

class IndexHandler(tornado.web.RequestHandler):

    def get(self, *args, **kwargs):
        self.render("index.html")

class ManagerHandler(tornado.web.RequestHandler):

    def get(self, *args, **kwargs):
        co = self.get_cookie("auth")
        if co == "1":
            self.render("manager.html")
        else:
            self.redirect("/index")

class LogoutHandler(tornado.web.RequestHandler):

    def get(self, *args, **kwargs):
        self.set_cookie("auth",'0')  # cookie的value必须是字符串
        self.redirect("/login")



class LoginHandler(tornado.web.RequestHandler):

    def get(self, *args, **kwargs):
        self.render("login.html",status_text="")

    def post(self, *args, **kwargs):
        username = self.get_argument("username",None)
        pwd = self.get_argument("password",None)

        if username == "alex" and pwd == "sb":
            self.set_cookie("auth", '1') # cookie的value必须是字符串
            self.redirect("/manager")

        else:
            self.render("login.html",status_text = "登陆失败")

settings = {
    "template_path" : "views",  # 模板路径的配置
}

#路由映射  路由系统

application = tornado.web.Application([
    (r"/index",IndexHandler),
    (r"/login",LoginHandler),
    (r"/logout",LogoutHandler),
    (r"/manager",ManagerHandler),

],**settings)


if __name__ == '__main__':
    # socket 运行起来

    application.listen(8880)
    tornado.ioloop.IOLoop.instance().start()

  

 

b、基本操作

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        if not self.get_cookie("mycookie"):
            self.set_cookie("mycookie", "myvalue")
            self.write("Your cookie was not set yet!")
        else:
            self.write("Your cookie was set!")
Code

b、签名

tornado 加密cookie的配置

settings = {
    "template_path":"views",
    "static_path":"statics",
    "cookie_secret":"dsfsfsafsdfasdf",
}

  

Cookie 很容易被恶意的客户端伪造。加入你想在 cookie 中保存当前登陆用户的 id 之类的信息,你需要对 cookie 作签名以防止伪造。Tornado 通过 set_secure_cookie 和 get_secure_cookie 方法直接支持了这种功能。 要使用这些方法,你需要在创建应用时提供一个密钥,名字为 cookie_secret。 你可以把它作为一个关键词参数传入应用的设置中:

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        if not self.get_secure_cookie("mycookie"):
            self.set_secure_cookie("mycookie", "myvalue")
            self.write("Your cookie was not set yet!")
        else:
            self.write("Your cookie was set!")
             
application = tornado.web.Application([
    (r"/", MainHandler),
], cookie_secret="61oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o/Vo=")
Code
def _create_signature_v1(secret, *parts):
    hash = hmac.new(utf8(secret), digestmod=hashlib.sha1)
    for part in parts:
        hash.update(utf8(part))
    return utf8(hash.hexdigest())


def _create_signature_v2(secret, s):
    hash = hmac.new(utf8(secret), digestmod=hashlib.sha256)
    hash.update(utf8(s))
    return utf8(hash.hexdigest())
内部算法
def create_signed_value(secret, name, value, version=None, clock=None,
                        key_version=None):
    if version is None:
        version = DEFAULT_SIGNED_VALUE_VERSION
    if clock is None:
        clock = time.time

    timestamp = utf8(str(int(clock())))
    value = base64.b64encode(utf8(value))
    if version == 1:
        signature = _create_signature_v1(secret, name, value, timestamp)
        value = b"|".join([value, timestamp, signature])
        return value
    elif version == 2:
        # The v2 format consists of a version number and a series of
        # length-prefixed fields "%d:%s", the last of which is a
        # signature, all separated by pipes.  All numbers are in
        # decimal format with no leading zeros.  The signature is an
        # HMAC-SHA256 of the whole string up to that point, including
        # the final pipe.
        #
        # The fields are:
        # - format version (i.e. 2; no length prefix)
        # - key version (integer, default is 0)
        # - timestamp (integer seconds since epoch)
        # - name (not encoded; assumed to be ~alphanumeric)
        # - value (base64-encoded)
        # - signature (hex-encoded; no length prefix)
        def format_field(s):
            return utf8("%d:" % len(s)) + utf8(s)
        to_sign = b"|".join([
            b"2",
            format_field(str(key_version or 0)),
            format_field(timestamp),
            format_field(name),
            format_field(value),
            b''])

        if isinstance(secret, dict):
            assert key_version is not None, 'Key version must be set when sign key dict is used'
            assert version >= 2, 'Version must be at least 2 for key version support'
            secret = secret[key_version]

        signature = _create_signature_v2(secret, to_sign)
        return to_sign + signature
    else:
        raise ValueError("Unsupported version %d" % version)
内部算法-加密
def _decode_signed_value_v1(secret, name, value, max_age_days, clock):
    parts = utf8(value).split(b"|")
    if len(parts) != 3:
        return None
    signature = _create_signature_v1(secret, name, parts[0], parts[1])
    if not _time_independent_equals(parts[2], signature):
        gen_log.warning("Invalid cookie signature %r", value)
        return None
    timestamp = int(parts[1])
    if timestamp < clock() - max_age_days * 86400:
        gen_log.warning("Expired cookie %r", value)
        return None
    if timestamp > clock() + 31 * 86400:
        # _cookie_signature does not hash a delimiter between the
        # parts of the cookie, so an attacker could transfer trailing
        # digits from the payload to the timestamp without altering the
        # signature.  For backwards compatibility, sanity-check timestamp
        # here instead of modifying _cookie_signature.
        gen_log.warning("Cookie timestamp in future; possible tampering %r",
                        value)
        return None
    if parts[1].startswith(b"0"):
        gen_log.warning("Tampered cookie %r", value)
        return None
    try:
        return base64.b64decode(parts[0])
    except Exception:
        return None


def _decode_fields_v2(value):
    def _consume_field(s):
        length, _, rest = s.partition(b':')
        n = int(length)
        field_value = rest[:n]
        # In python 3, indexing bytes returns small integers; we must
        # use a slice to get a byte string as in python 2.
        if rest[n:n + 1] != b'|':
            raise ValueError("malformed v2 signed value field")
        rest = rest[n + 1:]
        return field_value, rest

    rest = value[2:]  # remove version number
    key_version, rest = _consume_field(rest)
    timestamp, rest = _consume_field(rest)
    name_field, rest = _consume_field(rest)
    value_field, passed_sig = _consume_field(rest)
    return int(key_version), timestamp, name_field, value_field, passed_sig


def _decode_signed_value_v2(secret, name, value, max_age_days, clock):
    try:
        key_version, timestamp, name_field, value_field, passed_sig = _decode_fields_v2(value)
    except ValueError:
        return None
    signed_string = value[:-len(passed_sig)]

    if isinstance(secret, dict):
        try:
            secret = secret[key_version]
        except KeyError:
            return None

    expected_sig = _create_signature_v2(secret, signed_string)
    if not _time_independent_equals(passed_sig, expected_sig):
        return None
    if name_field != utf8(name):
        return None
    timestamp = int(timestamp)
    if timestamp < clock() - max_age_days * 86400:
        # The signature has expired.
        return None
    try:
        return base64.b64decode(value_field)
    except Exception:
        return None


def get_signature_key_version(value):
    value = utf8(value)
    version = _get_version(value)
    if version < 2:
        return None
    try:
        key_version, _, _, _, _ = _decode_fields_v2(value)
    except ValueError:
        return None

    return key_version
内部算法-解密

签名Cookie的本质是:

写cookie过程:

  • 将值进行base64加密
  • 对除值以外的内容进行签名,哈希算法(无法逆向解析)
  • 拼接 签名 + 加密值

读cookie过程:

  • 读取 签名 + 加密值
  • 对签名进行验证
  • base64解密,获取值内容

注:许多API验证机制和安全cookie的实现机制相同。

#!/usr/bin/env python
# -*- coding:utf-8 -*-
 
import tornado.ioloop
import tornado.web
 
 
class MainHandler(tornado.web.RequestHandler):
 
    def get(self):
        login_user = self.get_secure_cookie("login_user", None)
        if login_user:
            self.write(login_user)
        else:
            self.redirect('/login')
 
 
class LoginHandler(tornado.web.RequestHandler):
    def get(self):
        self.current_user()
 
        self.render('login.html', **{'status': ''})
 
    def post(self, *args, **kwargs):
 
        username = self.get_argument('name')
        password = self.get_argument('pwd')
        if username == 'wupeiqi' and password == '123':
            self.set_secure_cookie('login_user', '武沛齐')
            self.redirect('/')
        else:
            self.render('login.html', **{'status': '用户名或密码错误'})
 
settings = {
    'template_path': 'template',
    'static_path': 'static',
    'static_url_prefix': '/static/',
    'cookie_secret': 'aiuasdhflashjdfoiuashdfiuh'
}
 
application = tornado.web.Application([
    (r"/index", MainHandler),
    (r"/login", LoginHandler),
], **settings)
 
 
if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()
Demo-基于cookie进行用户验证
#!/usr/bin/env python
# -*- coding:utf-8 -*-
 
import tornado.ioloop
import tornado.web
 
class BaseHandler(tornado.web.RequestHandler):
 
    def get_current_user(self):
        return self.get_secure_cookie("login_user")
 
class MainHandler(BaseHandler):
 
    @tornado.web.authenticated
    def get(self):
        login_user = self.current_user
        self.write(login_user)
 
 
 
class LoginHandler(tornado.web.RequestHandler):
    def get(self):
        self.current_user()
 
        self.render('login.html', **{'status': ''})
 
    def post(self, *args, **kwargs):
 
        username = self.get_argument('name')
        password = self.get_argument('pwd')
        if username == 'wupeiqi' and password == '123':
            self.set_secure_cookie('login_user', '武沛齐')
            self.redirect('/')
        else:
            self.render('login.html', **{'status': '用户名或密码错误'})
 
settings = {
    'template_path': 'template',
    'static_path': 'static',
    'static_url_prefix': '/static/',
    'cookie_secret': 'aiuasdhflashjdfoiuashdfiuh',
    'login_url': '/login'
}
 
application = tornado.web.Application([
    (r"/index", MainHandler),
    (r"/login", LoginHandler),
], **settings)
 
 
if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()
Demo-Toando内部提供基于cookie进行用户验证

 

4 ajax  

什么是 ajax

ajax 即“Asynchronous JavaScript and XML”(异步 JavaScript 和 XML),也就是无刷新数据读取。

http 请求

首先需要了解 http 请求的方法(GET 和 POST)。

GET 用于获取数据。GET 是在 URL 中传递数据,它的安全性低,容量低。

POST 用于上传数据。POST 安全性一般,容量几乎无限。

ajax 请求

ajax 请求一般分成 4 个步骤。

1、创建 ajax 对象

在创建对象时,有兼容问题:

var oAjax = new XMLHttpRequest();   //for ie6 以上
var oAjax = new ActiveXObject('Microsoft.XMLHTTP'); //for ie6

合并上面的代码:

var oAjax = null;
if(window.XMLHttpRequest){
    oAjax = new XMLHttpRequest();
}else{
    oAjax = new ActiveXObject('Microsoft.XMLHTTP');
}

2、连接服务器

在这里会用到 open() 方法。open() 方法有三个参数,第一个参数是连接方法即 GET 和 POST,第二个参数是 URL 即所要读取数据的地址,第三个参数是否异步,它是个布尔值,true 为异步,false 为同步。

oAjax.open('GET', url, true);

3、发送请求

send() 方法。

oAjax.send();

4、接收返回值

onreadystatechange 事件。当请求被发送到服务器时,我们需要执行一些基于响应的任务。每当 readyState 改变时,就会触发 onreadystatechange 事件。

readyState:请求状态,返回的是整数(0-4)。

0(未初始化):还没有调用 open() 方法。

1(载入):已调用 send() 方法,正在发送请求。

2(载入完成):send() 方法完成,已收到全部响应内容。

3(解析):正在解析响应内容。

4(完成):响应内容解析完成,可以在客户端调用。

status:请求结果,返回 200 或者 404。

200 => 成功。

404 => 失败。

responseText:返回内容,即我们所需要读取的数据。需要注意的是:responseText 返回的是字符串。

oAjax.onreadystatechange=function(){
    if(oAjax.readyState==4){
        if(oAjax.status==200){
            fnSucc(oAjax.responseText);
        }else{
            if(fnFaild){
                fnFaild();
            }
        }
    }
};

  

ajax 1

***** Ajax概述 *****


1、Web应用程序:

    用户浏览器发送请求,服务器接收并处理请求,然后返回结果,往往返回就是字符串(HTML),浏览器将字符串(HTML)渲染并显示浏览器上。


2、传统的Web应用:

    一个简单操作需要重新加载全局数据


3、AJAX:

    AJAX,Asynchronous JavaScript and XML (异步的JavaScript和XML),一种创建交互式网页应用的网页开发技术方案。

    a. 异步的JavaScript:

        使用 【JavaScript语言】 以及 相关【浏览器提供类库】 的功能向服务端发送请求,当服务端处理完请求之后,【自动执行某个JavaScript的回调函数】。
        
        PS:以上请求和响应的整个过程是【偷偷】进行的,页面上无任何感知。

        利用该功能可以做:
            1、注册时,输入用户名自动检测用户是否已经存在。
            2、登陆时,提示用户名密码错误
            3、删除数据行时,将行ID发送到后台,后台在数据库中删除,数据库删除成功后,在页面DOM中将数据行也删除。(博客园)
        
        PS:传统的Web应用,每次请求都要重新获取所有的内容,而Ajax则只获取局部数据即可(节省数据流量)。

    b. XML:
        XML是一种标记语言,是Ajax在和后台交互时传输数据的格式之一
        

4、AJAX应用:

    麦子学院登陆、注册
    百度关键字搜索
    网页QQ、网页微信
    知乎、京东、天猫...
    几乎所有的网站均有应用
ajax 1
***** iframe实现伪“Ajax” *****

需求:
    用户输入URL,使用iframe将目标URL的内容加载到页面指定位置(局部刷新)

<!DOCTYPE html>
<html>

    <head lang="en">
        <meta charset="UTF-8">
        <title></title>
    </head>

    <body>

        <div>
            <p>请输入要加载的地址:<span id="currentTime"></span></p>
            <p>
                <input id="url" type="text" />
                <input type="button" value="刷新" onclick="LoadPage();">
            </p>
        </div>


        <div>
            <h3>加载页面位置:</h3>
            <iframe id="iframePosition" style="width: 100%;height: 500px;"></iframe>
        </div>


        <script type="text/javascript">
            x = new XMLHttpRequest();
            console.log(x);

            window.onload= function(){
                var myDate = new Date();
                document.getElementById('currentTime').innerText = myDate.getTime();

            };

            function LoadPage(){
                var targetUrl =  document.getElementById('url').value;
                document.getElementById("iframePosition").src = targetUrl;
            }

        </script>

    </body>
</html>
ajax 2
***** XmlHttpRequest实现Ajax(上)- XmlHttpRequest对象方法和属性的讲解 *****

1、概述
    Ajax主要就是使用 【XmlHttpRequest】对象来完成请求的操作,该对象在主流浏览器中均存在(除另类的IE),Ajax首次出现IE5.5中存在(ActiveX控件)

2、XmlHttpRequest对象的主要方法
    
    a. void open(String method,String url,Boolen async)
       用于创建请求
       
       参数:
           method: 请求方式(字符串类型),如:POST、GET、DELETE...
           url:    要请求的地址(字符串类型)
           async:  是否异步(布尔类型)

    b. void send(String body)
        用于发送请求

        参数:
            body: 要发送的数据(字符串类型)

    c. void setRequestHeader(String header,String value)
        用于设置请求头

        参数:
            header: 请求头的key(字符串类型)
            vlaue:  请求头的value(字符串类型)

    d. String getAllResponseHeaders()
        获取所有响应头

        返回值:
            响应头数据(字符串类型)

    e. String getResponseHeader(String header)
        获取响应头中指定header的值

        参数:
            header: 响应头的key(字符串类型)

        返回值:
            响应头中指定的header对应的值

    f. void abort()

        终止请求

3、XmlHttpRequest对象的主要属性

    a. Number readyState
       状态值(整数)

       详细:
          0-未初始化,尚未调用open()方法;
          1-启动,调用了open()方法,未调用send()方法;
          2-发送,已经调用了send()方法,未接收到响应;
          3-接收,已经接收到部分响应数据;
          4-完成,已经接收到全部响应数据;

    b. Function onreadystatechange
       当readyState的值改变时自动触发执行其对应的函数(回调函数)

    c. String responseText
       服务器返回的数据(字符串类型)

    d. XmlDocument responseXML
       服务器返回的数据(Xml对象)

    e. Number states
       状态码(整数),如:200、404...

    f. String statesText
       状态文本(字符串),如:OK、NotFound...
ajax 基础**** 3

 

***** XmlHttpRequest实现Ajax(下) *****

本节内容:
    基于XmlHttpRequest对象实现基本Ajax请求 以及 跨浏览器支持


1、发送Ajax请求:
    - xhr = new XmlHttpRequest()
    - xhr.onreadystatechange = func
    - xhr.open("GET", "url", true)
    - xhr.send()

    a、GET请求

    b、POST请求
        设置content-type


2、夸浏览器支持
    
    a. IE7+, Firefox, Chrome, Opera, etc.

        xhr = new XMLHttpRequest();

    b. IE6, IE5

        xhr = new ActiveXObject("Microsoft.XMLHTTP");
各浏览器支持

 

***** jQuery实现Ajax *****


1、jQuery
    
    jQuery其实就是一个JavaScript的类库,其将复杂的功能做了上层封装,使得开发者可以在其基础上写更少的代码实现更多的功能。

    
2、jQuery Ajax
    
    a. 概述
        
        jQuery 不是生产者,而是大自然搬运工。

        jQuery Ajax本质 XMLHttpRequest 或 ActiveXObject 

    b. 使用
        
        --- 下载导入jQuery(2.+版本不再支持IE9以下的浏览器) 
        
        --- Ajax操作

            jQuery.get(...)
                所有参数:
                     url: 待载入页面的URL地址
                    data: 待发送 Key/value 参数。
                 success: 载入成功时回调函数。
                dataType: 返回内容格式,xml, json,  script, text, html


            jQuery.post(...)
                所有参数:
                     url: 待载入页面的URL地址
                    data: 待发送 Key/value 参数
                 success: 载入成功时回调函数
                dataType: 返回内容格式,xml, json,  script, text, html


            jQuery.getJSON(...)
                所有参数:
                     url: 待载入页面的URL地址
                    data: 待发送 Key/value 参数。
                 success: 载入成功时回调函数。


            jQuery.getScript(...)
                所有参数:
                     url: 待载入页面的URL地址
                    data: 待发送 Key/value 参数。
                 success: 载入成功时回调函数。


            jQuery.ajax(...)

                部分参数:

                        url:请求地址
                       type:请求方式,GET、POST(1.9.0之后用method)
                    headers:请求头
                       data:要发送的数据
                contentType:即将发送信息至服务器的内容编码类型(默认: "application/x-www-form-urlencoded; charset=UTF-8")
                      async:是否异步
                    timeout:设置请求超时时间(毫秒)

                 beforeSend:发送请求前执行的函数(全局)
                   complete:完成之后执行的回调函数(全局)
                    success:成功之后执行的回调函数(全局)
                      error:失败之后执行的回调函数(全局)
                

                    accepts:通过请求头发送给服务器,告诉服务器当前客户端课接受的数据类型
                   dataType:将服务器端返回的数据转换成指定类型
                                   "xml": 将服务器端返回的内容转换成xml格式
                                  "text": 将服务器端返回的内容转换成普通文本格式
                                  "html": 将服务器端返回的内容转换成普通文本格式,在插入DOM中时,如果包含JavaScript标签,则会尝试去执行。
                                "script": 尝试将返回值当作JavaScript去执行,然后再将服务器端返回的内容转换成普通文本格式
                                  "json": 将服务器端返回的内容转换成相应的JavaScript对象
                                 "jsonp": JSONP 格式
                                          使用 JSONP 形式调用函数时,如 "myurl?callback=?" jQuery 将自动替换 ? 为正确的函数名,以执行回调函数

                                  如果不指定,jQuery 将自动根据HTTP包MIME信息返回相应类型(an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string

                 converters: 转换器,将服务器端的内容根据指定的dataType转换类型,并传值给success回调函数
                         $.ajax({
                              accepts: {
                                mycustomtype: 'application/x-some-custom-type'
                              },
                              
                              // Expect a `mycustomtype` back from server
                              dataType: 'mycustomtype'

                              // Instructions for how to deserialize a `mycustomtype`
                              converters: {
                                'text mycustomtype': function(result) {
                                  // Do Stuff
                                  return newresult;
                                }
                              },
                            });


        --- $ = jQuery

                   
            
jquery ajax

 

  

  

 

posted @ 2016-07-21 18:40  众里寻,阑珊处  阅读(1799)  评论(0编辑  收藏  举报
返回顶部