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

来源:互联网 发布:孤岛危机3神优化 编辑:程序博客网 时间:2024/06/05 09:22
在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去当数组处理,肯定是无法实现的。

0 0
原创粉丝点击