2016-12-01 6 views
0

私はAJAX経由でPHPスクリプトを実行すると、複数のボタンを持つスクリプトを持っています。私は結果をボタンで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); 
      } 
     }); 
    }); 
}); 
関連する問題