嘿我正在使用AJAX在我的网页上显示实时CSV数据,目前我的AJAX脚本点击按钮。但我希望它能够在不刷新或单击网格视图中的按钮的情况下显示数据,但我无法弄明白。
这是我的尝试: -
$(document).ready(function() {
$('#load_data').click(function() {
$.ajax({
url: "sample.csv",
dataType: "text",
success: function(data) {
var employee_data = data.split(/\r?\n|\r/);
var table_data = '<table class="table table-bordered table-striped">';
for (var count = 0; count < employee_data.length; count++) {
var cell_data = employee_data[count].split(",");
table_data += '<tr>';
for (var cell_count = 0; cell_count < cell_data.length; cell_count++) {
if (count === 0) {
table_data += '<th>' + cell_data[cell_count] + '</th>';
} else {
table_data += '<td>' + cell_data[cell_count] + '</td>';
}
}
table_data += '</tr>';
}
table_data += '</table>';
$('#employee_table').html(table_data);
}
});
});
});
<!DOCTYPE html>
<html>
<head>
<title>Click Load Data</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="table-responsive">
<h1 align="center">Please Click on Load Data</h1>
<br />
<div align="center">
<button type="button" name="load_data" id="load_data" class="btn btn-info">Load Data</button>
</div>
<br />
<div id="employee_table">
</div>
</div>
</div>
</body>
</html>
答案 0 :(得分:0)
轻松!您需要做的就是调用数据加载函数页面就绪,而不是将其添加为 .click()
回调:
$(document).ready(function() {
$.ajax({
url: "sample.csv",
dataType: "text",
success: function(data) {
var employee_data = data.split(/\r?\n|\r/);
var table_data = '<table class="table table-bordered table-striped">';
for (var count = 0; count < employee_data.length; count++) {
var cell_data = employee_data[count].split(",");
table_data += '<tr>';
for (var cell_count = 0; cell_count < cell_data.length; cell_count++) {
if (count === 0) {
table_data += '<th>' + cell_data[cell_count] + '</th>';
} else {
table_data += '<td>' + cell_data[cell_count] + '</td>';
}
}
table_data += '</tr>';
}
table_data += '</table>';
$('#employee_table').html(table_data);
}
});
});
&#13;
<!DOCTYPE html>
<html>
<head>
<title>Click Load Data</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="table-responsive">
<div id="employee_table">
</div>
</div>
</div>
</body>
</html>
&#13;