dongyanfeng0563 2017-10-17 11:17
浏览 48
已采纳

如何增加我的Ajax Like Button Speed(Jquery + PHP)

I have made a Ajax Like Button. After clicking the like button, it takes around 800ms - 1100 ms to do the following things:

  • Open insertlike.php page in the background using Jquery
  • Add the like to database in insertlike.php page
  • Confirm the like using JSON
  • Turn the like button color into green.

But Facebook's and other website's Like button works very fast.

Facebook directly change the like button color on click or it only change after adding the like into database?

This is my code:

index.php code to make ajax request

$(".insertlike").submit(function(e) {

    var data = $(this).serialize();
    var url = $(this).attr("action");
    var form = $(this); 
    $.post(url, data, function(data) { 
    try {
        data = JSON.parse(data);
        $(form).children("button").html(data.addremove + " Watchlist");
        $(form).children("input#addedornotsend").attr("value",data.addedornotsend); 

    } catch (e) {
        console.log("json encoding failed");
        return false;
    }
});
  return false;
});

Code inside insertlike.php

<?php

// Add to Database code 

$response = new \stdClass();
$response->addremove = "".$addremove."";
$response->addedornotsend = "".$addedornotsend."";
die(json_encode($response));

Any way to insert the like button speed? Maybe some php cache trick or something like that? I am still newbie.

Edit: This is my server response time speed test:

enter image description here

  • 写回答

2条回答 默认 最新

  • douquqiang1513 2017-10-17 11:30
    关注

    You can follow the Event Based Architecture. As soon as, user clicks on the like button, put the message in queue and then write to DB in background(Data Grid also can be a solution here, not sure if PHP has good data-grid solutions). And response to client will be sent back, assuming DB record is updated successfully.

    https://martinfowler.com/articles/201701-event-driven.html

    If you are updating single table, 800ms - 1100 ms does not seem to be acceptable timeline. Try to tune your SQL, check if the DB is properly tuned.Try to use ConnectionPool etc.

    In Facebook, a. apart from updating the DB on like, b. It also does other background processing like generating the NewsFeeds to relevant parties etc. I am speculating that FB might be doing part b using events based architecture rather than keeping the user to wait.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集