简体   繁体   English

如何通过Javascript更新数据库,然后重新加载

[英]How do update a database through Javascript, then reload

So, I'm making a website similar to FML and others, where people can post things and others can like/dislike and comment. 因此,我正在建立一个类似于FML和其他网站的网站,人们可以在其中发布事物,其他人可以喜欢/不喜欢和发表评论。

Right now, I have it so when somoene clicks "like", it's a link that calls "/like/(post id)", which calls a function that increments the database, then reloads the page. 现在,我有了它,所以当somoene单击“ like”时,它是一个调用“ / like /(post id)”的链接,该链接调用一个使数据库递增然后重新加载页面的函数。

I'd like to find a way to do this without having to do that. 我想找到一种无需这样做的方法。 A friend said to try ajax or javascript, but i'm completely uneducated in them. 一位朋友说尝试使用Ajax或javascript,但我对它们一无所知。

Does anyone have any pointers? 有人有指针吗?

I don't want to explain an AJAX request in its entirety, but this should point you in the right direction. 我不想完整地解释AJAX请求,但这应该为您指明正确的方向。 Instead of reloading the page, have /like/ return the number of likes. 不用重新加载页面,而是使用/ like /返回点赞的次数。 Then have the number in a selectable element, like 然后将数字包含在可选元素中,例如

<a id="postid" href="#" onclick="like(this);return false;" class="likebtn">Like</a>
<span id="postid-likes">0</span>

Then make the javascript function 然后制作javascript函数

<script>
function like(element) {
    xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            document.getElementById(element.id+"-likes").innerHTML=xmlhttp.responseText;
        }
    }
xmlhttp.open("GET","/like/"+element.id,true);
xmlhttp.send();
}
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM