在单击的按钮下通过Ajax显示PHP输出--不工作
我试图在单击的按钮下通过Ajax显示PHP输出,但我的代码不起作用 output.php在单击的按钮下通过Ajax显示PHP输出--不工作,php,jquery,ajax,Php,Jquery,Ajax,我试图在单击的按钮下通过Ajax显示PHP输出,但我的代码不起作用 output.php <?php if(isset($_POST['click_me'])){ echo "<p>Something</p>"; } ?> 看来,$(this)在success:function(response){}中的位置是问题的原因。代码也不会产生错误。我在SO和else上做了很多搜索,结果表明这应该是可行的。现在已经两个多小时了,我不明
<?php
if(isset($_POST['click_me'])){
echo "<p>Something</p>";
}
?>
看来,
$(this)
在success:function(response){}
中的位置是问题的原因。代码也不会产生错误。我在SO和else上做了很多搜索,结果表明这应该是可行的。现在已经两个多小时了,我不明白为什么它不起作用。你的猜测是正确的。回调函数中的$(this)
引用传入的对象。因此,在进行ajax调用之前,需要保存对按钮的引用。请将javascript更新为以下内容:
$(function(){
$('.same-class').click(function(){
$(this).next('p').append('Hello'); //Works
//save a reference to the button clicked.
var btn = $(this);
$.ajax({
url: 'output.php',
type: 'POST',
data: {click_me: 1},
success:function(response){
//use the button reference from above.
btn.next('p').append(response); //Does not work--does not do anything, does not produce errors either.
console.log(response); // works
$('same-class').append(response); //works but all buttons get appended
alert(response); //works
}
});
});
});
$(function(){
$('.same-class').click(function(){
$(this).next('p').append('Hello'); //Works
$.ajax({
url: 'output.php',
type: 'POST',
data: {click_me: 1},
success:function(response){
$(this).next('p').append(response); //Does not work--does not do anything, does not produce errors either.
console.log(response); // works
$('same-class').append(response); //works but all buttons get appended
alert(response); //works
}
});
});
});
$(function(){
$('.same-class').click(function(){
$(this).next('p').append('Hello'); //Works
//save a reference to the button clicked.
var btn = $(this);
$.ajax({
url: 'output.php',
type: 'POST',
data: {click_me: 1},
success:function(response){
//use the button reference from above.
btn.next('p').append(response); //Does not work--does not do anything, does not produce errors either.
console.log(response); // works
$('same-class').append(response); //works but all buttons get appended
alert(response); //works
}
});
});
});