Note: I have properly closed my div tags, the code was too long, hence posted the main snippet.
I tried with the onclick event but the table isn't showing up hence I changed my code back to original
<body>
<button onclick="fetchAndDisplayData()">Click me</button>
<table id="id01" class='table table-bordered table-striped'>
<tbody>
<thead>
<tr>
<th>Title </th>
</tr>
</thead>
</tbody>
</table>
<script>
function fetchAndDisplayData() {
var xmlhttp = new XMLHttpRequest();
var url = "http://localhost:8888/api/get/read1.php";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
myFunction(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = "";
var i;
for (i = 0; i < arr.length; i++) {
out += '<tr><td><a href="' + arr[i].link + '">' +
arr[i].title + '</a></td>';
out += '<td>' + arr[i].description + '<br></td>';
out += '<td>' + arr[i].log_time + '<br></td>';
out += '<td><a href="' + arr[i].link + '">' +
arr[i].link + '</a></td></tr>';
}
document.getElementById("#id01 tbody").innerHTML = out;
}
}
</script>
</body>
I want a button such that only when I click on the button, then I get those entries. What changes can I make? Please help me with the code. It's for a project.
Your script must be modified like this:
<script>
var show = true;
function fetchAndDisplayData() {
if (show) {
show = false
var xmlhttp = new XMLHttpRequest();
var url = "http://localhost:8888/api/get/read1.php";
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
myFunction(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
} else {
show = true;
myFunction([]);
}
}
function myFunction(arr) {
var out = "";
var i;
for (i = 0; i < arr.length; i++) {
out += '<tr><td><a href="' + arr[i].link + '">' +
arr[i].title + '</a></td>';
out += '<td>' + arr[i].description + '<br></td>';
out += '<td>' + arr[i].log_time + '<br></td>';
out += '<td><a href="' + arr[i].link + '">' +
arr[i].link + '</a></td></tr>';
}
document.getElementById("id01").getElementsByTagName('tbody')[0].innerHTML = out;
}
fetchAndDisplayData();
</script>
And your button should have this handler code instead:
<button onclick="fetchAndDisplayData()">Click me</button>
But there are other errors in your code (see my comment above), and I guess these changes won't make it work right away.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.