dpsq8476 2018-07-19 22:27
浏览 76
已采纳

从ajax存储变量

I am trying to store a variable from an ajax get request calling a PHP script. 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. 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

// 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

$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

  • 写回答

1条回答 默认 最新

  • douhuan6157 2018-07-19 22:45
    关注

    Ajax by default is asynchronous. (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. 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程