我正在尝试抄录程序员告诉我的内容。他和我可能做错了所有事情,因此我需要确保他和我做事正确。这是我们正在尝试做的事情:

我在网站上有一个页面,在该页面中,我有一个按钮。当您单击它时,我希望它(通过AJAX进行显示,因此页面不会刷新)


发送数据(时间捕获)到数据库
看到数据库记录了更改,然后又将另一个值返回给站点
这将依次更改按钮,请注意该按钮处于录制模式。


想到这种方式,按钮就是一个计时器。单击时,它将在DB中记录时间,并且在DB中还将状态更改为正在记录。由于它处于录制阶段,因此会以某种方式将其发送回网站页面,并更改显示正在录制的按钮。自然地,再次单击将停止它并在DB中记录时间。

以下是代码片段的设置方式(我认为不起作用):
*旁注:这是在Joomla中

页:

<script src="js/ajax_link.js" type="text/javascript"></script>
<div id="ajaxlink" onclick="loadurl('php/ticket_timer.php',<?php echo $row->id?>)">Start Time</div>


ajax_link.js

function loadurl(dest,ticket_id) {
jQuery.ajax({
      url: dest,
      type: "POST",
      data: "ticket_id="+ticket_id,
      success: function(msg){
         alert(msg);
         jQuery('#ajaxlink').text("Timer Stop");
      }
   });
}


ticket_timer.php

    <?php
    define( '_JEXEC', 1 );
    define( 'DS', DIRECTORY_SEPARATOR );
    define( 'JPATH_BASE', $_SERVER[ 'DOCUMENT_ROOT' ] );

    require_once( JPATH_BASE . DS . 'includes' . DS . 'defines.php' );
    require_once( JPATH_BASE . DS . 'includes' . DS . 'framework.php' );
    require_once( JPATH_BASE . DS . 'libraries' . DS . 'joomla' . DS . 'factory.php' );
    $mainframe =& JFactory::getApplication('site');

    $ticket_id = $_POST['ticket_id'];
     $user =& JFactory::getUser();
     $user_id=$user->get('id');

    //DB Query
$db = JFactory::getDbo();
    $query = $db->getQuery(true);
    $query->select($db->quoteName(array('id', 'ticket_id', 'user_id', 'times','current_time')));
    $query->from($db->quoteName('#__support_ticket_times'));
    $query->where($db->quoteName('ticket_id') . ' LIKE '. $db->quote($ticket_id));
    $query->where('ticket_id = '. $ticket_id, 'AND')
           ->where('user_id=' . $user_id );
    $db->setQuery($query);

    // Load the results as a list of stdClass objects (see later for more options on retrieving data).
    $results = $db->loadObjectList();
    $current_time=$results[0]->current_time;
    $times=$results[0]->times;
    $id_results = $db->loadColumn();
    $db->setQuery($idquery);


    $timesString = $times . ',' . date('Y-m-d g:i');
    echo($timesString);

    if(empty($results[0])){

        $values = array(max($id_results)+1, $ticket_id, $user_id, $db->quote(date('Y-m-d g:i')),$db->quote(date('Y-m-d g:i')));
        //echo "YOU GET NOTHING, MAKING NEW ROW";
        $columns = array('id', 'ticket_id', 'user_id', 'times','current_time');

        // Prepare the insert query.
        $insert_query = $db->getQuery(true);
        $insert_query
            ->insert($db->quoteName('#__support_ticket_times'))
            ->columns($db->quoteName($columns))
            ->values(implode(',', $values));

        // Set the query using our newly populated query object and execute it.
        $db->setQuery($insert_query);
        $db->query();


    }else{
        //echo("CURRENT TIME" . $current_time);
        if($current_time=='0000-00-00 00:00:00'){
            echo "NO TIME";
            $fields = array(
                            $db->quoteName('current_time'). '=' . $db->quote(date('Y-m-d g:i'))
                        );
        }
        // . $db->quote(date('Y-m-d g:i'))
        else{

            echo "ADD TIME";
            $fields = array($db->quoteName('times') . '='  . $db->quote($timesString) ,
                            $db->quoteName('current_time'). "='0000-00-00 00:00:00'"
                        );
        }
        $update_query = $db->getQuery(true);
        $conditions = array(
            $db->quoteName('user_id') . '=' . $db->quote($user_id),
            $db->quoteName('ticket_id') . '=' . $db->quote($ticket_id)
        );

        $update_query->update($db->quoteName('#__support_ticket_times'))->set($fields)->where($conditions);
        $db->setQuery($update_query);
        $db->query();
     //echo $update_query;
    }

    ?>


谁能建议如何使计时器重新启动计时器?我们是在屠宰这一切吗,有没有更好的方法编写代码呢?

最佳答案

您需要在PHP和HTML页面之间交换一些数据。当然,可以使用Javascript修改HTML页面。通常用于这种交换的符号是JSON。在此示例中,我们使用JSON进行以下操作:


将布尔值timerRunning发送到PHP,
更改PHP中的值,
发送回复,
修改HTML页面,并
timerRunning值存储在HTML元素中。


因此,对于初学者来说,我们使用HTML5 data-属性将一些数据从HTML元素传递到Javascript,如下所示:

<div id="ajaxlink" data-url="php/ticket_timer.php" data-ticketId="<?php echo $row->id; ?> " data-timerRunning="false">Start Time</div>


在您的Javascript中,我们访问上面设置的参数,然后通过AJAX将其发送到您的PHP脚本:

jQuery(document).ready(function($){
    // Add an 'onClick' handler to the element
    jQuery('#ajaxlink').on('click', function(event) {
        // Get the url and ticket_id from the element's 'data-' attributes
        var url = jQuery(this).data( 'url' );
        var data = {
            'ticketId' : jQuery(this).data( 'ticketId' ),
            'timerRunning' : jQuery(this).data( 'timerRunning' )
        }
        // Send an AJAX request
        jQuery.ajax({
            type: 'POST',
            url: url,
            data: data
        }).done( function(response) {
            // This runs when the AJAX request succeeds
            if ( 'undefined' == typeof( response.timerRunning ) ) {
                alert( 'The server didn\'t tell the timer state' );
                return;
            }
            // Store the value in the element
            jQuery('#ajaxlink').data( 'timerRunning', response.timerRunning );
            // Change the element HTML
            if ( response.timerRunning )
                jQuery('#ajaxlink').html( 'Stop Timer' );
            else
                jQuery('#ajaxlink').html( 'Start Timer' );
        }).fail( function(jqXHR, textStatus, errorThrown ) {
            // This runs when the AJAX request fails
            alert( 'The AJAX request failed with the error ' + errorThrown );
        });
    });
});


在您的PHP脚本中,检查timerRunning值并作出相应的反应:

if ( isset( $_POST['timerRunning'] ) ) { // Check that we got some value for 'timerRunning'
    if ( $_POST['timerRunning'] ) {
        // The 'timerRunning' value is TRUE, the timer is running, now stop it
        your_code_here_to_stop_the_timer();
        $reply = array( 'timerRunning' => false );
    } else {
        // The 'timerRunning' value is FALSE, the timer isn't running, now start it
        your_code_here_to_start_the_timer_and_whatever();
        $reply = array( 'timerRunning' => true );
    }
    // Send the correct header for a JSON response
    header('Content-type: application/json');
    // Send the $reply array encoded as JSON
    echo json_encode( $reply );
}

09-17 16:56
查看更多