使用Django向网页的页面js中传递一个数组的方法

在view.py中定义的响应函数
def app_config_edit(request):
    # 该函数功能是为页面提供编辑一个应用所使用的若干个配置文件信息的功能支持
    app_id = request.GET.get('id', '')
    app = get_object(App, id=app_id)
    # app.config_files是一个many to many类型字段
    temp = app.config_files 
    fileuri = []
    # 先从库表中获取到与该应用相关的全部配置文件路径与文件信息,即fileuri
    for i in temp.all():
        fileuri.append(i.fileuri)
    # 此时fileuri是一个python list类型,无法在页面js脚本中作为数组类型使用,需要转为json字符串
    fileuri_json = json.dumps(fileuri)
    #打印一下转换前后数据的不同格式
    print 'fileuri:',fileuri
    print 'fileuri_json:',fileuri_json
    if request.method == 'POST':
        af_post = AppConfigForm(request.POST)
        name = request.POST.get('name', '')
        try:
            pass
        except ServerError:
            pass
        else:
            if af_post.is_valid():
                af_save = af_post.save(commit=False)
                af_save.save()
                af_post.save_m2m()
                smg = u'应用配置文件 %s 修改成功' % name
            else:
                emg = u'应用SaltStack配置文件 %s 修改失败' % name
                return my_render('publish/error.html', locals(), request)
            return HttpResponseRedirect(reverse('app_detail')+'?id=%s' % app_id)
    return my_render('publish/app_config_edit.html', locals(), request)


后台打印的日志信息
fileuri: [u'/data/server/config/utf8.users', u'/data/server/config/important.properties']
fileuri_json: ["/data/server/config/utf8.users", "/data/server/config/important.properties"]
从以上数据格式,可以看出需要转为json格式的原因。


在app_config_edit.html 页面js中引用Django传递进来的数据变量
在页面中加入下面的js脚本,刷新页面,察看js脚本所拿到的数组数据:
<script>
    alert({{ fileuri_json|safe }})
</script>
刷新页面,弹出的窗口中显示的内容如下:
/data/server/config/utf8.users, /data/server/config/important.properties

为什么需要使用{{ fileuri_json|safe }}这样的形式?
Django的模板中会对HTML标签和JS等语法标签进行自动转义,原因显而易见,这样是为了安全。然后上面的"|safe"的作用正是关闭Django的自动转义功能。
如果不做这个干预,可以运行下面代码观察下效果:
<script>
    alert('{{ fileuri_json }}')
</script>
这是页面弹出的窗口内容:
[&quot;/data/server/config/utf8.users&quot;, &quot;/data/server/config/important.properties&quot;]

可以看到,Django把fileuri_json中的双引号全部转义了。
如果拿这个被转义后的字符串交给页面js去当数组处理,肯定是无法实现的。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值