简体   繁体   中英

Jquery Ajax click show page in a div

I have one question about jquery click to load url in a div using id.

I am trying when user clicking the class="open" id="1" then the ajax URL will open just id="openpage1" but the code showing in all id="openpageXX" what i am doing wrong here anyone can help me in this regard ?

$.base_url = 'http://localhost/';
$(".open").on('click', function() {
    var ID = $(this).attr("id");
    $("#openpage" + ID).slideToggle('fast');
    var URL = $.base_url + 'page.php';
    $.ajax({
      type: "POST",
      url: URL,
      cache: false,
      success: function(html) {
        if (html) {
           $(".page_area").html(html);
        }
      }
    });

    return false;
  });

Html

<!--First Post Started-->
<div class="post_area" id="1">
  <div class="open" id="1">Click for 1</div>
  <div class="opened_page" id="openpage1">
    When user click (class=open id 1 then ajax page will need to open just here)
  </div>
</div>
<!--First Post finished-->

<!--Second post started-->
<div class="post_area" id="2">
<div class="open" id="2">Click for 2</div>
  <div class="opened_page" id="openpage2">
    When user click (class=open id 2 then ajax page will need to open just here)
  </div>
</div>
<!--Second Post finished-->

I see 3 issues

  1. I strongly suggest using unique non-numeric IDs - but my code no longer needs ID - I use datza-id to hold the information for the link
  2. you need to find the closest opened_page - you try page_area which is not in your HTML
  3. I would cache the clicked object to use in the success

like this:

<div class="post_area">
  <div class="open" data-id="1">Click to open</div>
  <div class="opened_page">
    When user click (class=open id 1 then ajax page will need to open just here)
  </div>
</div>

using

$(function() {
  $(".open").on('click', function(e) {
     e.preventDefault(); // in chase you change to a link or button
     var $this = $(this),
           URL = $.base_url + 'page.php?page='+$this.data("id"),
         $page = $this.next("opened_page"); // sibling
     $.ajax({
       type: "POST",
       url: URL,
       cache: false,
       success: function(html) {
         if (html) {
            $page.html(html).slideToggle('fast');; // sibling
         }
       }
    });
  });
});

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM