我在这里测试了一些代码,基本上 html 文件代码的目的是根据用户单击的 h3 标题从 php 文件中回显值。
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<h3 id="random1" name="random_request1">Click here to get number from php</h3>
<p id="randomnumber">Number here</p>
<h3 id="random2" name="random_request2">Click here to get string from php</h3>
<p id="randomtext">Text here</p>
<script>
$('#random1').click(function()
{
//On click: ask php to get me a random text file
$.ajax({
type: 'POST',
url: "action.php",
success: function(newrandom)
{
$('#randomnumber').replaceWith(newrandom);
}
});
});
$('#random2').click(function()
{
$.ajax({
type: 'POST',
url: "action.php",
success: function(newrandom)
{
$('#randomtext').replaceWith(newrandom);
}
});
});
</script>
</body>
</html>
这是 action.php 代码:
<?php
if ($_POST['random_request1']) {
$random = rand();
echo $random;
}
else if ($_POST['random_request2']){
echo 'abcd';
}
?>
不出所料,php 无法识别 $_POST[] 中的 random_request1 和 2 名称。在这种情况下,我认为我仍然没有很好地掌握 POST 函数来自己回答这个问题。
最佳答案
只使用一次点击事件
$('h3[id^="random"]').on('click',function()
{
//On click: ask php to get me a random text file
$.ajax({
type: 'POST',
url: "action.php",
data: {id : $(this).attr('id')},
success: function(newrandom)
{
$('#randomnumber').replaceWith(newrandom);
}
});
});
在你的 action.php 中
<?php
$id = $_POST['id'];
?>
关于javascript - PHP 和 Ajax : how to find out which object did the user click to pass to php?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30169129/