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.

图片转代码服务由CSDN问答提供 功能建议

我需要将数据从XML配置文件传递给JavaScript。 应用程序需要完全脱机工作(我将使用应用程序缓存和localstorage),我计划使用PHP生成页面。 是否有一种简单的方法可以将XML放置在输出文档中,使其不会干扰标准HTML解析,但仍然可以使用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>
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题