2016-12-01 64 views
0

我有脚本与多个按钮,当点击运行一个PHP脚本通过AJAX。现在我想用按钮在div中显示结果。我已经试过这个和父母,但都没有工作。如何在ajax调用后更新div标签?

以下示例:点击时.showme我希望结果显示在#here div内的同一父级内。

$(document).ready(function() { 
 
    $('.showme').bind('click', function() { 
 

 
    var id = $(this).attr("id"); 
 
    var num = $(this).attr("class"); 
 
    var poststr = "request=" + num + "&moreinfo=" + id; 
 
    $.ajax({ 
 
     url: "../../assets/php/testme.php", 
 
     cache: 0, 
 
     data: poststr, 
 
     success: function(result) { 
 
     $(this).getElementById("here").innerHTML = result; 
 
     } 
 
    }); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class='request_1 showme' id='rating_1'>More stuff 1 
 
    <div id="here"></div> 
 
</div> 
 
<div class='request_2 showme' id='rating_2'>More stuff 2 
 
    <div id="here"></div> 
 
</div> 
 
<div class='request_3 showme' id='rating_3'>More stuff 3 
 
    <div id="here"></div> 
 
</div>

+1

你有没有在你的浏览器的控制台任何错误? – Max

+2

元素'id'在文档中应该是唯一的。具有相同'id'的多个元素是_invalid_HTML,并且在尝试使用JS/jQuery定位元素(通常只返回第一个实例)时可能会有未定义的行为。如果你想用JS/jQuery来定位多个元素,可以使用类来代替。 – jmoerdyk

回答

0

我认为这会做:

$(document).ready(function() { 
    $('.showme').bind('click', function() { 

     //keep the element reference in a variable to use in ajax success 
     var _this = $(this); 

     var id = $(this).attr("id"); 
     var num = $(this).attr("class"); 
     var poststr = "request=" + num + "&moreinfo=" + id; 
     $.ajax({ 
      url: "../../assets/php/testme.php", 
      cache: 0, 
      data: poststr, 
      success: function (result) { 
       //use the element reference you kept in variable before ajax call instead of $(this) 
       //also use jQuery style, getElementById is undefined if you call after $(this) 
       //.find() will call it's child in any level, also better you use classes instead of using same id multiple times 
       _this.find("#here").html(result); 
      } 
     }); 
    }); 
});