在javascript中回应php

时间:2018-04-21 22:54:58

标签: javascript php xmlhttprequest

尝试在MySQL表格中向所有用户显示消息'屏幕使用xmlhttp,toastr alert和php。

我使用xmlhttp.open("GET","includes/ajax/user/general/messages.php?username=<?php echo $_SESSION['username']; ?>",true);这是SQL所在的地方,我把它放在5秒循环上,所以它每5秒检查一次messages.php

然后我这样做:

xmlhttp.send();

$.toast({
heading: <?php echo json_encode($messageInfo['title']); ?>,
text: <?php echo json_encode($messageInfo['message']); ?>,
position: 'top-right',
loaderBg: '#ff6849',
icon: <?php echo json_encode($messageInfo['type']); ?>,
hideAfter: 6000,
stack: 6
});

然而,这仅输出&#39; null&#39;作为标题和&#39; null&#39;作为文本。

messages.php:

<?php

    if (!isset($_SERVER['HTTP_REFERER'])){
        die;
    }

    ob_start();
    require_once '../../../app/config.php';
    require_once '../../../app/init.php';

    if (!empty($maintaince)){
        die();
    }


    if (!($user -> LoggedIn()) || !($user -> notBanned($odb)) || !($user->isAdmin($odb))){
        die();
    }


    $username = $_GET['username'];

    if(empty($username)){
        die();
    }

    $SQLGetInfo = $odb -> prepare("SELECT * FROM `live_messages` WHERE id = 1");
    $SQLGetInfo -> execute(array($_SESSION['ID']));
    $messageInfo = $SQLGetInfo -> fetch(PDO::FETCH_ASSOC);

    $type = $messageInfo['type'];
    $title = $messageInfo['title'];
    $message = $messageInfo['message'];


?>

编辑:如果我将messages.php中的PHP代码直接放入运行此脚本的文件中,那么它会成功从数据库中取出,但是这没有任何帮助,因为我希望在实时。

编辑: 完整的脚本

<script>

                window.setInterval(function(){

                    var xmlhttp;

                    if (window.XMLHttpRequest){

                        xmlhttp = new XMLHttpRequest();

                    }

                    else{

                        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

                    }

                    xmlhttp.open("GET","includes/ajax/user/general/messages.php?username=<?php echo $_SESSION['username']; ?>",true);



                    xmlhttp.send();

                    $.toast({
                    heading: <?php echo json_encode($title); ?>,
                    text: <?php echo json_encode($message); ?>,
                    position: 'top-right',
                    loaderBg: '#ff6849',
                    icon: <?php echo json_encode($type); ?>,
                    hideAfter: 6000,
                    stack: 6
                    });


                }, 5000);


                </script>

3 个答案:

答案 0 :(得分:0)

我认为您对如何使用XHR请求有轻微的误解。 XHR请求的工作方式与浏览器请求类似,使用您向我们展示的代码,您没有为响应注册处理程序。

请参阅MDN上的POST示例:https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send

现在,为了访问由main处理的数据,您将不得不发回适当的JSON响应。

即。 messages.php

然后将其传递回您的XHR请求加载处理程序。

W3学校有一个“好的”例子,说明它们如何组合在一起:https://www.w3schools.com/js/js_json_php.asp

编辑:我提供了一个工作代码示例,它实质上是w3schools链接中内容的直接复制和粘贴。

header('Content-Type: application/json'); echo json_encode($messageInfo);

test.html

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script> var xmlhttp = new XMLHttpRequest(); // When the XHR Request receives a response from the server // this function will be called. xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { // This function is necessary to parse the JSON sent back // from the server. // Note: It can fail, so you'll want to make sure it actually parsed // the response. var message = JSON.parse(this.responseText); // Here is an example of how you would use it with your $.toast call // $.toast({ // heading: message.heading, // text: message.body, // position: 'top-right', // loaderBg: '#ff6849', // icon: message.type, // hideAfter: 6000, // stack: 6 // }); document.getElementById("toast_title").innerHTML = message.title; document.getElementById("toast_body").innerHTML = message.body; } }; xmlhttp.open("GET", "demo_file.php", true); xmlhttp.send(); </script> </head> <body> <div id="toast_title"></div> <div id="toast_body"></div> </body> </html>

demo_file.php

答案 1 :(得分:0)

可能是

<script>
var username = "<?php echo $_SESSION['username']; ?>";
var title = JSON.parse("<?php echo json_encode($title); ?>");
var message = JSON.parse("<?php echo json_encode($message); ?>");
var type = JSON.parse("<?php echo json_encode($type); ?>");

window.setInterval(function(){

                var xmlhttp;

                if (window.XMLHttpRequest){

                    xmlhttp = new XMLHttpRequest();

                }

                else{

                    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

                }

                xmlhttp.open("GET","includes/ajax/user/general/messages.php?username="+username ,true);



                xmlhttp.send();

                $.toast({
                heading: title,
                text: message,
                position: 'top-right',
                loaderBg: '#ff6849',
                icon: type,
                hideAfter: 6000,
                stack: 6
                });
            }, 5000);
</script>

答案 2 :(得分:0)

我不明白为什么那些甚至不知道问题是什么的人都在随意尝试答案,但是:

<?php

        if (!isset($_SERVER['HTTP_REFERER'])){
              header("HTTP/1.0 404 Not Found")
                die('HTTP_REFERER is not set');
        }

        require_once '../../../app/config.php';
        require_once '../../../app/init.php';

        if (!empty($maintaince)){
              header("HTTP/1.0 404 Not Found")
                die('maintaince is not set');
        }


        if (!($user -> LoggedIn()) || !($user -> notBanned($odb)) || !($user->isAdmin($odb))){
              header("HTTP/1.0 404 Not Found")
                die('User not logged in, banned, or isn\'t an admin');
        }


        $username = $_GET['username'];

        if(empty($username)){
              header("HTTP/1.0 404 Not Found")
                die('username is not set');
        }

        $SQLGetInfo = $odb -> prepare("SELECT * FROM `live_messages` WHERE id = 1");
        $SQLGetInfo -> execute(array($_SESSION['ID']));
        $messageInfo = $SQLGetInfo -> fetch(PDO::FETCH_ASSOC);

        $type = $messageInfo['type'];
        $title = $messageInfo['title'];
        $message = $messageInfo['message'];

        echo json_encode(array(
            'type' => $type,
            'title' => $title,
            'message' => $message,
        ));
        exit();
?>

<script>

window.setInterval(function(){

        var xmlhttp;

        if (window.XMLHttpRequest){
                xmlhttp = new XMLHttpRequest();
        } else {
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }

        xmlhttp.open("GET","includes/ajax/user/general/messages.php?username=<?php echo $_SESSION['username']; ?>",true);

        xmlhttp.addEventListener("load", function () {
            if (xmlhttp.status === 200) {
                var res = JSON.parse(xmlhttp.responseText);
                $.toast({
                        heading: res.title,
                        text: res.message,
                        position: 'top-right',
                        loaderBg: '#ff6849',
                        icon: res.type,
                        hideAfter: 6000,
                        stack: 6
                });
            } else {
                $.toast({
                        heading: 'ERROR',
                        text: 'AN ERROR OCCURED' + xmlhttp.responseText,
                        position: 'top-right',
                        loaderBg: '#ff6849',
                        icon: '',
                        hideAfter: 6000,
                        stack: 6
                });
            }
        };

        xmlhttp.send();
}, 5000);


</script>