我正在尝试通过使用AJAX单击链接来更新mysql,但我已经碰壁了。我有代码,但它不起作用。
这是AJAX:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
//bind a listener to "click" event on links with class "markviewed"
$('a.markviewed').click(function(event) {
//prevent default behavior just in case
event.preventDefault();
//get ids from clicked <a>
var myid = $(this).attr('data-myid');
var postid = $(this).attr('data-postid');
//ping the address to mark clicked link as viewed
$.ajax('http://mywebsite.com/mark_viewed.php?myid=' + myid + '&postid=' + postid');
//redirect to the link in the href attribute
window.location.href = $(this).attr('href');
});
});
</script>
这应创建一个href类,点击后会点击mywebsite.com/mark_viewed.php,它会使用$myid
和$postid
发送的关键变量更新我的数据库。
这是mark_viewed.php:
<?php
$con=mysqli_connect("XXX","XXX","XXX","XXX");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// get values sent from address bar
$myid=$_GET['myid'];
$postid=$_GET['postid'];
mysqli_query($con,"UPDATE comments SET status='viewed' WHERE to_id ='$myid' AND id='$postid'");
mysqli_close($con);
?>
最后这是用户看到的链接:
$myid = $row['user_id']; // my id
$name = $row['board_name']; // collection name
$boardid = $row['board_id']; // collection id
$postid = $row['pin_id']; // post id
$url = $row['pin_url']; // image url
echo "<li><a href='/board/pins/$boardid/$postid' data-myid=' . $myid . ' data-postid=' . $postid . ' class='markviewed'>";
echo "<img src='$url' height='50' width='50'>";
echo "New comment in $name.";
echo "</a></li>";
然而,在测试中它不起作用。点击时的链接只会浏览到包含新评论的页面,而且数据库不受影响。
我做错了什么?
答案 0 :(得分:0)
$(document).ready(function() {
$('a.markviewed').click(function(event) {
event.preventDefault();
var myid = $(this).attr('data-myid');
var postid = $(this).attr('data-postid');
$.ajax('http://mywebsite.com/mark_viewed.php?myid=' + myid + '&postid=' + postid).done(function(){
window.location.href = $(this).attr('href');
});
});
});
问题是ajax函数被调用(但在位置更改之前没有完成)。所以它正在改变位置。所以等待ajax函数完成并在成功回调中更改位置
答案 1 :(得分:-1)
您的AJAX
来电没有足够的时间来完成。 AJAX
中的第一个A代表异步,这意味着下一个命令window.location.href = $(this).attr('href');
会在AJAX
调用之后立即运行,然后才能完成。
将重定位移至AJAX
回调,例如
//ping the address to mark clicked link as viewed
$.ajax('http://mywebsite.com/mark_viewed.php?myid=' + myid + '&postid=' + postid', function(){
//redirect to the link in the href attribute
window.location.href = $(this).attr('href');
});
您还应考虑添加等待动画,以防您的通话需要很长时间。
作为一个良好的编码实践,最好避免劫持这样的点击,并在目标页面的开头用PHP记录所需的信息,然后打印新的页面内容。
如果链接是外部链接,您可以链接到重定向页面(redirect.php?target_url = www.externallink.com),该页面记录所需信息并立即调用header(Location: "www.externallink.com")
。这样,用户就不会在您的网站中看到任何可察觉的延迟。