如何使用Ajax向指定用户发送数据而不需要指定用户的请求?


How can I send data with Ajax to the specified user without request from the specified user

假设用户成功完成登录操作。现在我有了一个来自指定用户的会话,它如下所示:

$_SESSION['login_user'] = $username;

我在网上搜索了这个问题,我明白我应该使用Ajax。我看到了这个链接,但是我不明白我应该使用哪种方法将数据发送给指定的用户

$_SESSION变量是全局可用的,因此您可以在呈现要在其中显示消息的页面的文件中使用它。只有当您希望避免用户登录后页面重新加载时,才需要使用Ajax请求。

例如view.php:

echo 'Welcome back'.$_SESSION['login_user'].'!';

您可以通过回显将数据(来自服务器)发送回客户机。例如,您可能希望从服务器获取日期时间,以防止客户端篡改它:

服务器(假设返回json)

$datetime = new Datetime();
$res = array(
    'date' => $datetime->format('d-m-Y'),
    'hour' => $datetime->format('H'),
    'minutes' => $datetime->format('i'),
    'seconds' => $datetime->format('s'),
);
echo json_encode($res);

客户端(假设使用jquery)

$.ajax({
            url: 'url_to_the_above_file.php',
            type: 'post',
            data: { // dummy post data that can be read server-side
                action : 'some value',
            },
            dataType: 'json',
            beforeSend : function() {
                //some action BEFORE send here
            },
            success: function(data, textStatus, jqXHR){
                //here is your response from the server
                console.log(date);
                console.log(hour);
                console.log(minutes);
                console.log(seconds);
            },
            error: function(data) {
                console.log("we are in error");
                console.log(data);
            },
            complete: function() {
                //some action AFTER send here
            }
        });