duanmianxue2687 2018-02-09 18:54
浏览 40
已采纳

显示多个Ajax html响应

The $('.my-button').click(function(e) function is supposed to show the output of the display.php, which just contains some mysql query and the output in html. It works so far, but as I am looping the button itself for each post, the function only works for the first button. I need to make the script understand, that for each button it should only show the results for that button. But how to insert some individual ID to the $(".responsecontainer").html(response);? I tried with $(".responsecontainer" + id).html(response); getting "id" before via parameters, but it seems that this id must be hardcoded.

Here is the full code:

$(document).ready(function() {
$('.my-button').click(function(e) {                
  $.ajax({    //create an ajax request to display.php
    type: "GET",
    url: "display.php",             
    dataType: "html",   //expect html to be returned                
    success: function(response){                    
        $(".responsecontainer").html(response); 
        //alert(response);
    }

And this is the button and DIV to show results:

<input type="button" class="my-button" value="'.$plus.'" />
<div class="responsecontainer" id="'.$plus.'" align="center">
</div>      

Noting that $plus is always unique.

  • 写回答

2条回答 默认 最新

  • duanjiao8871 2018-02-09 19:05
    关注
    • Use data-attributes to store the related DIV's id.
    • When a button is clicked get the data-attribute, i.e: data-target-id.
    • With that id you can execute a selector as follow: #div_1 and insert the received HTML.
    • DON'T use value to target your DIV, the button's value is the text for your buttons, just imagine if your button texts are filled using a kind of i18n translation.

    $(document).ready(function() {
      $('.my-button').click(function(e) {
          var targetId = $(this).data('target-id');
          /*$.ajax({ //create an ajax request to display.php
              type: "GET",
              url: "display.php",
              dataType: "html", //expect html to be returned                
              success: function(response) {*/
                $(`#${targetId}`).html(`Response = ${targetId}`);
              /*});
          });*/
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type="button" data-target-id='div_1' class="my-button" value="Click me!" />
    <div id='div_1' class="responsecontainer" align="center">
    </div>
    
    <input type="button" data-target-id='div_2' class="my-button" value="Click me!" />
    <div id='div_2' class="responsecontainer" align="center">
    </div>
    
    <input type="button" data-target-id='div_3' class="my-button" value="Click me!" />
    <div id='div_3' class="responsecontainer" align="center">
    </div>

    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?