创建用于计算点击次数并在cookie中存储值的php函数

问题描述 投票:-1回答:3

目前尝试将按钮和复选框的点击量存储到cookie或会话中,然后将其保存到数据库中。我的想法是为每个按钮和复选框创建一个计数功能。

php cookies count click
3个回答
1
投票

要实现在页面元素上记录命中的目标,您需要使用某种形式的http请求与将记录命中的PHP服务器进行通信 - 在数据库,易失性会话或文件中。这里的示例使用简单的ajax函数,但您可以使用更灵活的fetch api。

这个演示应该为您提供创建记录到db的解决方案的基础知识...

<?php
    session_start();
    /* store the click in a session or log to DB */
    /*
        using a session will only give accurate information for a single user and a single session
        so to actually record this information for all users and across time and space you really
        need to use a database or, at least some sort of file.

    */
    if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['action'], $_POST['name'], $_POST['value'] ) && $_POST['action']=='log-click' ){

        $name=$_POST['name'];
        $value=$_POST['value'];
        $svar='clicks';

        /* create the session variable to record hits */
        if( !isset( $_SESSION[ $svar ] ) ) $_SESSION[ $svar ]=new stdClass;

        /* assign initial value or increment hit count */
        if( !isset( $_SESSION[ $svar ]->{$name} ) )$_SESSION[ $svar ]->{$name}=1;
        else $_SESSION[ $svar ]->{$name}++;

        /* send something back to the ajax callback - to be processed however suits */
        exit( json_encode( array( 
                'name'      =>  $name,
                'value'     =>  $value,
                'time'      =>  time(),
                $svar       =>  $_SESSION[ $svar ]->{$name}
                )
            )
        );
    }


?>
<!DOCTYPE html>
<html>
    <head>
        <script>
            /* very simple ajax function */
            const ajax=function(m,u,p,c,o){
                with( new XMLHttpRequest() ){
                    onreadystatechange=function(e){
                        if( this.status==200 && this.readyState==4 ){
                            c.call( this, this.response, this.getAllResponseHeaders(), o )
                        }
                    }
                    let params=Object.keys( p ).map( k=>{
                        return [k,p[k]].join('=')
                    }).join('&');

                    if( m.toUpperCase()=='GET' ){
                        u='?'+params;
                        params=null;                        
                    }
                    open( m.toUpperCase(), u, true );
                    setRequestHeader('Content-Type','application/x-www-form-urlencoded');
                    send( params );
                }
            };


            document.addEventListener('DOMContentLoaded',e=>{
                /* Find elements of these types and bind an event listener to each */
                let col=document.querySelectorAll( 'input[type="button"], input[type="checkbox"]' );

                /* iterate through each DOM element and assign listener */
                Array.prototype.slice.call( col ).forEach( input=>{
                    input.addEventListener('click', e=>{
                        /* construct arguments for ajax request */
                        let method='post';
                        let url=location.href;
                        let params={ action:'log-click', name:e.target.name, value:e.target.value };
                        let callback=function(r){
                            document.querySelector( 'output' ).innerText=r
                        }
                        let options={};

                        /* make the ajax request */
                        ajax.call( this, method, url, params, callback, options )
                    })
                })
            });
        </script>
    </head>
    <body>
        <form method='post'>
            <fieldset>
                <input type='button' name='bttn_1' value='Click here to win a mystery prize' />
                <input type='checkbox' name='checkbox_1' value=1 />
            </fieldset>

            <fieldset>
                <input type='button' name='bttn_2' value='Click here to win luxury items' />
                <input type='checkbox' name='checkbox_2' value=1 />
            </fieldset>

            <fieldset>
                <input type='button' name='bttn_3' value='Click here to win a car' />
                <input type='checkbox' name='checkbox_3' value=1 />
            </fieldset>

            <fieldset>
                <input type='button' name='bttn_4' value='Click here to win a dream holiday' />
                <input type='checkbox' name='checkbox_4' value=1 />
            </fieldset>
        </form>

        <output></output>
    </body>
</html>

1
投票

你可以使用javascript XHR(ajax)将点击数据发送到php脚本或使用javascript cookies insted ...


1
投票

您需要添加监控点击事件的javascript代码,并且每次点击都可以激活ajax调用以更新数据库中的计数器。

© www.soinside.com 2019 - 2024. All rights reserved.