dp926460 2014-06-26 00:24
浏览 22

将大量数据从php加载到javascript?

I read this question php array loading into javascript to see what I can do to load a large amount of data from PHP to Javascript, it seems I may have implemented it wrong. Javascript processes and formats the data after it comes in from PHP which loads the data from a database, the data is placed into the client-side session storage so that the data can be worked with by each page. (If there is a better way to do this please let me know).

This is in one .php file.

<?php

session_start();

require_once 'classes/Membership.php';

$membership = new Membership();

$confirmation = $membership->confirm_membership();

if ($confirmation){

    $data = $membership->get_data("assump");

    echo '<script>var data = '.json_encode($data) .';</script>';

}

?>

This is in a separate .js file

function loadData(){

    // All sessionStorage can be accessed by any javascript file

    for(var i = 0; i < data.length; i++){

        sessionStorage.setItem("assump" + i, data[i]);

    }

}

However no values are being loaded. Is this even possible to do?

EDIT: I moved the javascript into the .php file where var data was being created from the php script at the top of the file, I placed the function loadData() into a script tag after the body tag in the html.

  • 写回答

1条回答 默认 最新

  • dongshi6969 2014-06-26 00:52
    关注

    This should work fine. However you may experience some problem with the scope (not 100% sure). And here is my suggestion.

    Attach your variable to the window object. That's everywhere and you can access it everywhere.

    echo '<script>window.mydata = '.json_encode($data) .';</script>';
    

    Ideally you could include this line before your other scripts are included, but this should be fine. I am not sure about your session storage because I would just interact with the data directly from anywhere:

    window.alert(window.mydata.blah...);
    

    I've always found that by assigning essentially global variables, to the window object you know exactly that there are no scope problems and it's always there for you.

    You can also check for it's existence using:

    if(window.mydata!=undefined){ ... }
    

    or the following but the above implies you are checking that it actually exists where as the below could not be true if window.mydata does exist but is set to false or 0 or something like that...

    if(window.mydata){ ... }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么