好的,我有这个代码:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
function get() {
$.post('tt.php', { name : $(this).attr('id') }, function(output) {
$('#age').html(output).show();
});
}
</script>
</head>
<body>
<input type="text" id="name"/>
<a id="grabe" href="javascript: get()">haller</a>
<div id="age">See your name</div>
</body>
</html>
以下是我想要的:从用户通过jQuery点击的锚标记中获取锚标记的id,然后将其传递到PHP文件中。然后,PHP文件将把用户单击的锚标记的id名称回显到jQuery,jQuery将把输出显示到指定的元素中。
这是PHP文件:
<?
$name=$_POST['name'];
if ($name==NULL)
{
echo "No text";
}
else
{
echo $name;
}
?>
这样绑定您的事件,因为您使用的是jQuery
$('a').click(function(){
$.post('tt.php', { name : $(this).attr('id') }, function(output) {
$('#age').html(output).show();
});
});
并从href
中删除javascript
<a id="grabe" href="#">haller</a>
<a id="kane" href="#">haller 2</a>
$('#grabe').click(function() {
$('#age').load('yourphp.php', {'name':$(this).prop('id')});
});
您可以使用$(this)
访问代码中几乎所有关于"是什么让您来到这里"的内容。您还需要一个事件的监听器。在下面这个过于简短的例子中,我让它监听<span class="edit_area">
跨度的任何点击。
<script>
$(document).ready(function(){
$('span.edit_area').click( function(){
var fieldname = $(this).attr('id');
...
});
});
我不知道你为什么要向服务器发送一个id,然后从ajax调用中再次接收该id,因为它已经在你的客户端脚本中了。不管怎样,这就是代码。
此代码将为所有具有名为"crazyLink
"类的标签执行此功能,并在id为anotherCrazyDiv
的div中显示从服务器页面接收的数据
HTML
<a class="crazyLink" href="#">I am crazy</a>
<a class="crazyLink" href="#">I am crazy2</a>
<div id="anotherCrazyDiv"></div>
编写脚本
$(function(){
$(".crazyLink").click(function(){
var id=$(this).attr("id");
$.post("data.php", { name : id } ,function(data){
$("#anotherCrazyDiv").html(data);
});
return false; // to prevent normal navigation if there is a valid href value
});
});
请记住,在您的场景中,id变量中的值和data变量中的数值(在从ajax调用获得响应之后)是相同的。
您可能需要将javascript与html分离。它让事情变得更容易。它可能看起来像这样。
HTML
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"> </script>
<script type="text/javascript" src="javascript/somescript.js"></script>
</head>
<body>
<input type="text" id="name"/>
<a id="grabe" class="someclass">haller</a>
<div id="age">See your name</div>
</body>
</html>
javascript
$(document).ready(function() {
$('.someclass').click(function() {
$('#age').load(
url: 'tt.php',
data: { name: $(this).attr('id')}
);
});
});