前言:
在使用了 ajax 的 load 方法加载页面之后,导致之前的 echarts 绘图无法在新加载的页面使用,在网上搜索了一番之后,有的说不能使用 load 方法,要使用 get 或者 post 方法,有的说要重写 load 方法的,这些方法都不适合我,所以现在记录我自己的方法,供大家参考。
需求:
- 使用 ajax load() 方法在 A.php 页面加载 B.php 页面。
- 加载之后在 B.php 页面使用 Echarts 绘制图形。
方法:
A.php
... 其他代码段 ...
<div id="newPageContents">
</div>
... 其他代码段 ...
B.php
<!-- css样式最好写在单独的css文件中,并且需要指定div的长宽 -->
<style>
.main {
width: 900px;
height: 500px;
}
</style>
<div class="my-4 w-100 main" id="main" width="900" height="380"></div>
js代码 ( js文件请在 A.php 文件里加载 ):
$(document).ready(function () {
$('#newPageContents').load('/your_page_url', { // 你自己 load 的页面 url
'key': value, '_token': token, // Laravel post 提交需要 token
}, function (response, status, xhr) {
if (response.length > 50) {
myChart = echarts.init(document.getElementById('main'));
exampleFunc(data);
}
});
function exampleFunc(data) {
window.onresize = function () {
myChart.resize();
};
$.ajax({
url: "/your_ajax_url", // 你自己的 ajax url
type: "POST",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: {
"key": data,
},
success: function (result) {
var option = {
tooltip: {
trigger: 'axis',
axisPointer: { type: 'cross' }
},
xAxis: {
name: '登录日期',
data: result['date']
},
yAxis: {
name: '登陆次数'
},
series: [
{
name: '登陆次数',
type: 'line',
data: result['times'],
}
]
};
// 使用刚指定的配置项和数据显示图表。
myChart.setOption(option);
}
});
}
});
解释:
1. 关键点在于 load 方法里的回调函数,load 写法:
$("#selector").load(url, { key: value }, function(response, status, xhr) {
if (response.length > 50) {
myChart = echarts.init(document.getElementById('main'));
adminLoginRecord(data);
}
});
2. 这里的 if (response.length > 50) 的意思是 load 传递回来的内容为页面显示的代码,但是由于我的 response 里除了页面的 tag 内容,还有错误信息 (如果有错误),所以只能通过 response 的长度来判断是否需要使用 Echarts 来绘制图形。因为错误信息的 string 小于 50。
总结:
以上,就是使用 ajax load 方法加载新页面之后,在新页面使用 Echarts 绘制图形的方法。如果有不明白或者更好更简便的方法,可以在下面评论交流,谢谢。