How can you make a vote-up-down button like in Stackoverflow?

前端 未结 4 1335
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-02 06:28

Problems

  1. how to make an Ajax buttons (upward and downward arrows) such that the number can increase or decrease
  2. how to save the actio
4条回答
  •  悲&欢浪女
    2020-12-02 07:12

    You create the buttons, which can be links or images or whatever. Now hook a JavaScript function up to each button's click event. On clicking, the function fires and

    • Sends a request to the server code that says, more or less, +1 or -1.
    • Server code takes over. This will vary wildly depending on what framework you use (or don't) and a bunch of other things.
    • Code connects to the database and runs a query to +1 or -1 the score. How this happens will vary wildly depending on your database design, but it'll be something like UPDATE posts SET score=score+1 WHERE score_id={{insert id here}};.
    • Depending on what the database says, the server returns a success code or a failure code as the AJAX request response.
    • Response gets sent to AJAX, asynchronously.
    • The JS response function updates the score if it's a success code, displays an error if it's a failure.

    You can store the code in a variable, but this is complicated and depends on how well you know the semantics of your code's runtime environment. It eventually needs to be pushed to persistent storage anyway, so using the database 100% is a good initial solution. When the time for optimizing performance comes, there are enough software in the world to cache database queries to make you feel woozy so it's not that big a deal.

提交回复
热议问题