这可能是一个愚蠢的问题,请耐心等待:
我正在使用ajax加载一个json文件,然后在高图表中显示数据:代码如下:
$.ajax({
cache: false,
dataType: "json",
url: "{% static 'money/data/highchartpiesam.json' %}",
success: function (json) {
console.log("haha i have read the json")
console.log('Success', this.url)
$('#containerHighChartJSONPie').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: 1, //null,
plotShadow: false
},
title: {
text: 'Expenses per Types of Expenditures'
},
tooltip: {
pointFormat: '{point.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %',
style: {
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
}
}
}
},
series: [{
type: 'pie',
name: 'Type of Expenditure',
data: json
}]
});
}
});
此代码效果很好,但如果您在上面的代码中看到 url:url: "{% static 'money/data/highchartpiesam.json' %}" 用户的文件名,sam 的文件名是 highchartpiesam.json ,ram 的文件名是 highchartpieram.json 等 即不同用户的文件名会有所不同(根据我的 django 代码),并且登录的用户名将附加到工作 highchartpie.json
为了完成这项工作,我想创建一个 url 字符串,然后将该字符串放入 url:但这似乎不起作用:(
我所做的是将上面的代码更改为以下:
$(document).ready(function () {
console.log("aah document is loaded ")
console.log("File Name code");
var a = '{\% static '.concat('\'money/data/highchartpie').concat('{{ user.username }}').concat('.json\'').concat("%}");
console.log("File Name code : Value of initial string is a is ", a);
var chartFileName = a;
$.ajax({
cache: false,
dataType: "json",
url: chartFileName,
success: function (json) {
console.log("haha i have read the json")
console.log('Success', this.url)
$('#containerHighChartJSONPie').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: 1, //null,
plotShadow: false
},
title: {
text: 'Expenses per Types of Expenditures'
},
tooltip: {
pointFormat: '{point.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %',
style: {
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
}
}
}
},
series: [{
type: 'pie',
name: 'Type of Expenditure',
data: json
}]
});
}
});
});
我仍然得到 connsole.log 输出,直到:
"File Name code : Value of initial string is a is " "{% static 'money/data/highchartpiesam.json'%}"
但此后什么也没有。
有人可以就此提出建议吗?
最佳答案
这不可能行得通。您肯定意识到模板标签是在后端处理的,并且只有渲染的内容发送到浏览器?让 JS 生成看起来像模板标签的字符串是没有意义的,因为到那时渲染步骤已经过去了。
相反,您需要让 Django 生成文件的基本路径,并将其余部分添加到 JS 中。很简单:
var base_path = '{% static "money/data/" %}';
var user = '{{ user.username }}'
var full_url = [base_path, 'highchartpie', user, '.json'].join('')
关于javascript - 将脚本中的变量字符串替换为 ajax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25906865/