最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Display table on button click using ajax - Stack Overflow

programmeradmin4浏览0评论

I have a page that looks like this:

"Default List Name" is the name of the current page displayed. There are two buttons below and then a table which is the Default List table. Once I click Btn1, it will just re-display the default list table, but when I click Btn2, another table will be displayed, replacing the default list table. Let's call the second table "Second List". Once the table changes, the title "Default List Name" will also change to "Second List Name".

I am going to use AJAX for this so that real time button click and displaying of the corresponding table are applied. But I am still new to AJAX so I am having quite a hard time.

Here's my current code:

var title = $("#title").text();
var btn1 = $("#btn1");
var btn2 = $("#btn2");

/** If one of the buttons is clicked after another and then displays a table, the previous ajax that displayed the previous table, will be removed **/
$(document).ready(function() {
    btn1.on("click", function() {
        displayDefaultList();
    });
    btn2.on("click", function() {
        displaySecondList();
    });
});

function displayDefaultList(){
    console.log("display default list table");
    /*$.ajax({
        type: 'GET',
        dataType: 'json',
        cache: false,
        url: 'url to current page (not sure)',
        async: false
    }).*/
}

function displaySecondList(){
    console.log("display second list table");
}

I hope I'm making my self clear and hope you guys can help me.

I have a page that looks like this:

"Default List Name" is the name of the current page displayed. There are two buttons below and then a table which is the Default List table. Once I click Btn1, it will just re-display the default list table, but when I click Btn2, another table will be displayed, replacing the default list table. Let's call the second table "Second List". Once the table changes, the title "Default List Name" will also change to "Second List Name".

I am going to use AJAX for this so that real time button click and displaying of the corresponding table are applied. But I am still new to AJAX so I am having quite a hard time.

Here's my current code:

var title = $("#title").text();
var btn1 = $("#btn1");
var btn2 = $("#btn2");

/** If one of the buttons is clicked after another and then displays a table, the previous ajax that displayed the previous table, will be removed **/
$(document).ready(function() {
    btn1.on("click", function() {
        displayDefaultList();
    });
    btn2.on("click", function() {
        displaySecondList();
    });
});

function displayDefaultList(){
    console.log("display default list table");
    /*$.ajax({
        type: 'GET',
        dataType: 'json',
        cache: false,
        url: 'url to current page (not sure)',
        async: false
    }).*/
}

function displaySecondList(){
    console.log("display second list table");
}

I hope I'm making my self clear and hope you guys can help me.

Share Improve this question asked Apr 12, 2016 at 3:54 Ethelene LaverneEthelene Laverne 2892 gold badges7 silver badges21 bronze badges 3
  • 1 You can have a look at post: stackoverflow./questions/446594/… if you really want to have control over the ajax requests, abort them when needed. OR you can disable the second button until loading bar is displayed while loading first table. – pavanjoshi Commented Apr 12, 2016 at 4:03
  • See api.jquery./load – guest271314 Commented Apr 12, 2016 at 4:08
  • @Ethelene how you handle ajax response? – uzaif Commented Apr 12, 2016 at 4:21
Add a ment  | 

2 Answers 2

Reset to default 2

I just wrote this for you just to show you that you can always show and hide your tables

$(document).ready(function(){
  $("#mytable1").show();
        $("#mytable2").hide();

        $("#button1").click(function(){
            $("#text").html("Default List Name");
            $("#mytable2").hide();
            $("#mytable1").show();

        });

        $("#button2").click(function(){
            $("#mytable1").hide();
            $("#mytable2").show();
            $("#text").html("Second List Name");
        });
});
<script src="https://ajax.googleapis./ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<div id = "text">Default List Name</div>
<button id = "button1">Button1</button>
    <button id = "button2">Button2</button>
    <table  id = "mytable1" border = "1">
        <tr>
            <td>text1</td>
            <td>text1</td>
            <td>text1</td>
        </tr>
        <tr>
            <td>text2</td>
            <td>text2</td>
            <td>text2</td>
        </tr>
        <tr>
            <td>text3</td>
            <td>text3</td>
            <td>text3</td>
        </tr>
        <tr>
            <td>text4</td>
            <td>text4</td>
            <td>text4</td>
        </tr>
    </table>
 <br/>
    <table id = "mytable2" border = "1">
        <tr>
            <td>box1</td>
            <td>box1</td>
            <td>box1</td>
        </tr>
        <tr>
            <td>box2</td>
            <td>box2</td>
            <td>box2</td>
        </tr>
        <tr>
            <td>box3</td>
            <td>box3</td>
            <td>box3</td>
        </tr>
        <tr>
            <td>box4</td>
            <td>box4</td>
            <td>box4</td>
        </tr>
    </table>

NOW for your ajax, you should just simply hide one of the tables based on the button that was clicked, and then load the data to your specific table. This works for me. Hope it helps :)

Here's AJAX:

   $(document).ready(function(){

    $("#button1").click(function(){
        $("#mytable2").hide();

        $.ajax({
            url:'app.php',
            type: "GET",
            data: ""
            dataType: 'json',
            success: function(data){
                $.each(data, function(key, value){
                    $("table #mytable1").append("<tr><td>" +
                                        "ID :" + value.ID +
                                        "Name :"+ value.Name +
                                        "Age :" + value.Age + 
                                        "</td><tr>");
                                       .........
                });
            }
        });
    });


    $("#button2").click(function(){
        $("#mytable1").hide();

        $.ajax({
            url:'app.php',
            type: "GET",
            data: ""
            dataType: 'json',
            success: function(data){
                $.each(data, function(key, value){
                    $("table #mytable2").append("<tr><td>" +
                                        "ID :" + value.ID +
                                        "Name :"+ value.Name +
                                        "Age :" + value.Age + 
                                        "</td><tr>");
                                       .........
                });
            }
        });
    });
 });

I created this fiddle for you: https://jsfiddle/8bakcfub/.

Basically, each button click will simulate a call to an API that returns a very simple JSON object. On success, the code parses the response, empties the table and appends a new row to it with the data, and finally changes the title.

Note that the code is pretty much the same for both buttons, except for (a) the JSON returned from AJAX, and (b) the title :)

HTML:

<p id="title">
  This title will be replaced...
</p>
<button id="btn1">
  First list
</button>
<button id="btn2">
  Second list
</button>
<table id="table">
  <thead>
    <th>Col 1</th>
    <th>Col 2</th>
  </thead>
  <tbody>
  </tbody>
</table>

JS:

var btn1 = $("#btn1");
var btn2 = $("#btn2");

$(document).ready(function() {
  btn1.on("click", function() {
    displayDefaultList();
  });
  btn2.on("click", function() {
    displaySecondList();
  });
});

function displayDefaultList() {
  $.ajax({
    type: 'POST',
    dataType: 'json',
    url: '/echo/json/',
    async: false,
    data: {
      json: JSON.stringify({
        row: [1, 2]
      })
    },
    success: function(result) {
      $('#title').text('first list');
      $('#table tbody').remove();
      var newRow = '<tbody><tr><td>' + result.row[0] + '</td></tr><tr><td>' + result.row[1] + '</td></tr></tbody>';
      $('#table').append(newRow);
    }
  });
}

function displaySecondList() {
  $.ajax({
    type: 'POST',
    dataType: 'json',
    url: '/echo/json/',
    async: false,
    data: {
      json: JSON.stringify({
        'row': [3, 4]
      })
    },
    success: function(result) {
      $('#title').text('second list');
      $('#table tbody').remove();
      var newRow = '<tbody><tr><td>' + result.row[0] + '</td></tr><tr><td>' + result.row[1] + '</td></tr></tbody>';
      $('#table').append(newRow);
    }
  });
}
发布评论

评论列表(0)

  1. 暂无评论