下面是放置在循环内部的一段代码
for( some condition will go here )
{
echo "<td>
<a href='event.php?event_id=".$datee2. "&action=Details'>". ($i - $startday + 1) . "</a>
</td>";
}
点击它后,用户将被引导到event.php页面,同时,event_id和操作参数也将被转发,
但不是这样我想通过ajax将event.php页面调用到第一个页面,为此我尝试了这个
<script>
function chk()
{
$.ajax({
type:"post",
url: "event.php",
data:dataString,
cache:false,
success: function(html)
{
$('#msg').html(html);
}
}) ;
return false;
}
</script>
echo
"<td>
<a onclick='return chk()'>". ($i - $startday + 1) . "</a>
</td>";
但它不起作用,我也希望你每次点击都能通过ajax将event_id和action参数转发到event.php页面,有人能告诉我们如何做到这一点吗?
以下是
<a href="#" class="myclass" data-id="'.$someID.'" data-action="'.$someAction.'">
js将是
$(".myclass").on("click", function(){
var id = $(this).data("id");
var action = $(this).data("action");
$.ajax({
type : "post",
url : "event.php",
data : {
"id":id,
"action":action
},
cache : false,
success : function(html)
{
$('#msg').html(html);
}
});
});
应该是这样的
$.ajax({
type : "post",
url : "event.php",
data : {
"event_id":"-id of the event-",
"action":"-0action paramter-"
},
cache : false,
success : function(html)
{
$('#msg').html(html);
}
});
构建添加类的循环:
echo "<td>
<a class='anEvent' href='event.php?event_id=".$datee2. "&action=Details'>". ($i - $startday + 1) . "</a>
</td>";
然后使用:
<script type="text/javascript">
$('.anEvent').on('click',function(e){
e.preventDefault();
$('#msg').load($(this).attr('href'));
})
</script>
您可以使用data
属性和$.post
请求,如果您可以避开inline-events
并为链接提供标识符(在我的示例中为ajax-link
类,因为您的代码将从循环中创建,所以我们不必使用id
,因为id在同一文档中应该是唯一的),那么您可以使用它将click
事件附加到a
标记,请查看以下示例:
PHP:
"<td>
<a class='ajax-link' data-event-id=".$datee2." data-action='Details'>". ($i - $startday + 1) . "</a>
</td>";
JS:
$('body').on('click', '.ajax-link', function(e){
e.preventDefault();
var url = $(this).data('action');
var event_id = $(this).data('event-id');
$.post(url, {event_id: event_id, action: action},
function(html)
{
$('#msg').html(html);
}
});
})
希望这能有所帮助。
问题是您正在单击开始加载event.php的链接。您应该使用event.prventDefault()来避免chk()函数中的默认操作。
function chk()
{
event.preventDefault();
$.ajax({
type:"post",
url: "event.php",
data:dataString,
cache:false,
success: function(html)
{
$('#msg').html(html);
}
});
return false;
}