通过ajax实现类似的功能?

时间:2018-03-11 15:44:30

标签: javascript jquery node.js ajax

我的网站即将完成。然而,最后一件事是一个问题。我想实现一个ajax喜欢的功能。

当用户点击按钮时,ajax应该触发并增加数据库中以及显示屏上的值。

我的问题是一切正常,除了ajax部分,我几乎没有使用ajax而不了解如何实现它。 Ajax应该将URL与node.js的路由匹配并显示结果。这是相关的代码。

这是我的把手模板:

 <div class="row">

    {{#each event}} {{#is this.event ../eventName }}

    <div class="col s12 m3 13 al">
        <div class="card ">
            <div class="card-image">
                <img src="/Small/{{this.imageId}}.JPG">
            </div>
            <div class="card-action">

                <a id="like_feature" href="/{{this.imageId}}/love" class="like">Love
                    <i class="material-icons fav">favorite</i>
                </a>


                <span class="rank">Rank: xxx
                    <i class="material-icons eq">equalizer</i>
                </span>
                {{!-- {{this.imageId}} --}}
            </div>
            <div class="card-action">
                <span class="number_of_likes">Number of likes: {{this.vote}}</span>
            </div>

        </div>
    </div>

    {{/is}} {{/each}}


</div>

这是我处理类似功能的路线

app.get('/:id/love', (req, res) => {
console.log("Hitting");
var image_Id = req.params.id;
var query = {
    "imageId": image_Id
}
var update = {
    $inc: {
        vote: 1
    }
}

likeImformation.findOneAndUpdate(query, update, function (err, voted) {
    if (err) {
        res.status(404)
    } else {
        console.log(voted);
        res.send("loved");
    }
});})

这就是我能够通过阅读教程来构建的ajax,我不知道如何在此之后移动

$(function(){
$('#like_feature').click(function (e){
    e.preventDefault();
    $.ajax({
        url:'love',
        type:'GET',
        success:function(){
            console.log("it is been liked");
        },
        error: function () {
          console.log("Not been liked");
        }
    })
})

})

1 个答案:

答案 0 :(得分:0)

function callAjax() {
    // the XMLHttpRequest returns the ajax object that has several cool methods, so you store it in the request variable
    // @data contains the $GET[liked],$GET[whatever] since we are using GET method, if you're using PHP as a server side language
    var request = new XMLHttpRequest(),
        url = 'place_here_the_url_only',
        data = 'liked=1&whatever=dataYouWantToSendToServerFromBrowser',
        token = document.querySelector('meta[name="csrf-token"]').content;

    // when the server is done and it came back with the data you can handle it here
    request.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            // do whatever you want!
            console.log("The request and response was successful!");
       }
    };

    // method get, your giving it the URL, true means asynchronous
    request.open('GET', url + "?" + data, true);
    // set the headers so that the server knows who is he talking to, I'm using laravel 5.5
    request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=UTF-8');
    // Token needed
    request.setRequestHeader('X-CSRF-TOKEN', token);
    // then you send the data and wait for the server to return the response
    request.send();
}

这是vanilla javascript版本 但是,现在在服务器上获取$ _GET ['likes'],验证并检查它是否为1更新数据库。