win10下,webpy0.4使用AJAX,后端正确响应json字符串到前端的方式

结合前人和自己的实践经验写下此文。

那就开门见山吧。

当前端使用AJAX,且dataType:"json"时,webpy后端该如何正确地响应json字符串给前端呢?

正确方式总结了两种(已在win10下测试):

一.

import json

return json.dumps({'msg':'ng'})

二.

 return '{"msg":"ng"}'

注意:这种方式必须是,单引号在外双引号在内,否则报错。

至于 web.header('content-type','text/json'),此行代码,经测试,可有可无。

由此看来,后端响应到前端所谓的json格式,就是json字符串啊。

三.注意事项

还有一点值得注意,那就是 $ 符号了。

 $ 符号是jQuery的简写方式,但是webpy也用它,且并未给出替代方案。

值得庆幸的是jQuery 还是比较大气的,给出了替代方案,遇到冲突,能够迁就,退让。

那么 jQuery 就别再使用它了,就用  jQuery 自己, 问题得以解决,完美!

至于  

var jq = $.noConflict();

jq(function(){

    jq("button").click(function(){

        jq("p").text("jQuery 仍然在工作!");

    });

});

异或

$.noConflict();/jQuery.noConflict();

 jQuery(function($){

    $("button").click(function(){

        $("p").text("jQuery 仍然在工作!");

    });

});

我都试过了,统统不行。

type:"POST",中post 可大写,可小写。

async:"true",中true的引号,可有可无。

jquery-1.11.3.js,必须放在static下,否则,网页不能自动刷新,

导致jQuery AJAX无效。

html模板可以放在templates下,也可以放在根目录的其他文件夹下,

但是不能放在根目录下,或static下,否则,报错。

三.我的代码如下:

前端代码 jobStatus4.html:

$def with (totalNum, finishedNum)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>jobStatus</title>
    <script src="../static/js/jquery-1.11.3.js"></script>
    <script>
        jQuery(function(){            
            jQuery.ajax({
                url:"/getJobStatus", 
                data:{"finishedNum": jQuery('em').html()},
                type:"POST",
                dataType:"json",
                async:"true",
                error:function (xhr,status,error) {
                    alert(xhr.responseText);
                    alert(xhr.status);
                    // alert(xhr.readyState);
                    alert(status);
                    alert(error);                   
                },
                success:function (data,status,xhr) {
                    // console.log(data);
                    var msg = data.msg;
                    // console.log(msg);                                 
                    if(msg=="ng"){
                        window.location.reload();
                    }else if(msg=="ok"){
                        window.alert("ok");
                    }
                },
            });
        });
    </script>
</head>
<body>
    {"totalNum": $totalNum, "finishedNum": <em>$finishedNum</em>}
</body>

</html>

后端代码:

import web
from monitor1 import *
import time
import json
render = web.template.render('templates/')
# getJobStatus 的刷新周期.
DELAY = 0.5
urls = (
    '/pushConvertJob/jpgdirectory/(.*)', 'writeFile',
    '/getJobStatus', 'getJobStatus',
    '/getJobResult', 'getJobResult',
)

class writeFile:
    def GET(self, jpgdirectory):
        with open('picture_catalog.txt', "a") as f:
            f.write(jpgdirectory + '\n')
        main()
        return {"msg": "ok"}

class getJobStatus:
    def GET(self):
        totalNum, finishedNum = count()
        # print(totalNum, finishedNum)
        return render.jobStatus4(totalNum, finishedNum)
    def POST(self):
        # 此行代码可有可无。
        # web.header('content-type','text/json')
        # print("aaa")
        totalNum,_ = count()
        # print(totalNum)
        # print(type(totalNum))
        i = web.input()
        # print("i:", i) 
        finishedNum = i.get('finishedNum')
        # print('finishedNum', finishedNum)
        # print(type(finishedNum))
        if int(finishedNum) == totalNum:
            print('ooo')            
            # return json.dumps({'msg':'ok'})
            return '{"msg":"ok"}'
        else:
            print('nnn')
            time.sleep(DELAY)
            # windows下,webpy 正确响应json的两种方式。
            # return json.dumps({'msg':'ng'})
            return '{"msg":"ng"}'


class getJobResult:
    def GET(self):
        pngDirectory = "C:/Users/RH-AS03/Desktop/高生杰/webpy框架相关/文件监听及处理/png"
        # return {"pngDirectory": pngDirectory}
        return render.JobResult(pngDirectory)


if __name__ == "__main__":
    app = web.application(urls, globals())
    app.run()


猜你喜欢

转载自blog.csdn.net/weixin_42193179/article/details/80610263