dpzjl68484 2014-05-27 17:36
浏览 83
已采纳

通过缓存的HTML将XML配置文件传递给JavaScript

I need to pass data from an XML configuration file to JavaScript. The application needs to work entirely offline (I'll be using application cache and localstorage) and I was planning to generate the page using PHP. Is there an easy way to place the XML in the outputted document in such a way that it will not interfere with standard HTML parsing but still be easily accessible using JavaScript.

  • 写回答

1条回答 默认 最新

  • doucai4274 2014-05-27 18:03
    关注

    If, as suggested by the comments, you can use json instead, then you can set it to an html tags data attribute:

    <?php $settings = array('name'=>'john');?>
    <div id="mydiv" data-settings="<?php echo json_encode($settings); ?>"> <!-- --> </div>
    

    Then retrieve it in javascript:

    var mydiv=document.getElementById('mydiv');
    var settings=JSON.parse(mydiv.dataset.settings);
    alert(settings.name); //alerts john
    

    or simply echo it into a script tag:

    <script type="javascript">
        var settings=<?php echo json_encode($settings); ?>;
    </script>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 vmware exsi重置后的密码
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 UE5#if WITH_EDITOR导致打包的功能不可用
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题