简体   繁体   English

从ajax存储变量

[英]Storing variable from ajax

I am trying to store a variable from an ajax get request calling a PHP script. 我试图从调用PHP脚本的ajax get请求存储变量。 I need the variable that the information is stored in to persist within an interval function. 我需要将信息存储在其中的变量以保留在区间函数中。 I see the data and the call is successful on the PHP script but the variable is undefined when I go back to the code that contains the ajax request. 我看到了数据,并且在PHP脚本上调用成功,但是当我返回到包含ajax请求的代码时,该变量未定义。 So my question is how do I go about storing this data into a variable and making sure the variable data is retained until I leave the webpage? 所以我的问题是我该如何将这些数据存储到变量中并确保在离开网页之前保留变量数据?

index.php index.php

// ajax repeated call on home page
<script type="text/javascript">
    var storedVariable0;
    $(document).ready(function() 
    {
        setInterval(function () 
        {
                        // ensure data was retained will be undefined first time through
            document.write(storedVariable0);

            $.ajax({
            url: '/fetchdatabase.php',
            type: 'GET',
            dataType: 'json',
            })
            .done(function(json){
            storedVariable0 = JSON.stringify(json);
            document.write(storedVariable0);
            });

                        // ensure data is retained outside of the scope of the ajax call
            document.write(storedVariable0);
        }, 1000 ); //update every second
    });
</script>

fetchdatabase.php fetchdatabase.php

$sql = "SELECT content FROM messages ORDER BY id DESC LIMIT 1";
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result) > 0) 
{
    // output data of each row
    while($row = mysqli_fetch_assoc($result)) 
    {
        echo json_encode($row);
    }
}

thanks for any help 谢谢你的帮助

Ajax by default is asynchronous. 默认情况下,Ajax是异步的。 (synchronous is deprecating). (同步已弃用)。

By asynchronous, it means that your third block of document.write(storedVariable0) will most likely be executed before the Ajax done block. 通过异步,这意味着您的document.write(storedVariable0)的第三个块很可能会在Ajax done块之前执行。 So, you will get undefined before done has completed. 因此,在完成之前,您将变得不确定。

Doing asynchronous is recommended wau and you need change your way of coding and make sure all access to storedVatiable0 happened after done finishes. 建议执行wau异步操作,并且您需要更改编码方式,并确保在完成操作后所有对storedVatiable0的访问均已发生。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM