将PHP变量传递到外部JavaScript(或jQuery)文件的最有效方法 [英] Most efficient way to pass PHP variables to external JavaScript (or jQuery) file

查看:60
本文介绍了将PHP变量传递到外部JavaScript(或jQuery)文件的最有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读了有关该问题的几篇文章,发现是最简单的解决方案,这是我的代码:

js 内部PHP 代码

<script>
    <!--// 
      var jsBaseurl = <?php echo json_encode(BASE_URL."/"); ?>;
      var jsTitle = <?php echo json_encode($h1_title); ?>;
      var jsSubtl = <?php echo json_encode($h2_title);?>;
    //-->
</script>
<script src="external.js"></script>

外部 .js

var siteURL=jsBaseurl;
alert(siteURL+jsTitle+jsSubtl)

工作正常,我的问题与以下评论有关: biplav :

警告:这可能会杀死您的网站.示例:

<?php $myVarValue = '<!--<script>'; ?>

有关详细信息,请参见此问题.解决方案:使用 JSON_HEX_TAG 可以逃脱<和>(需要PHP 5.3.0). -

此方法的另一个缺点是会影响初始页面的加载时间. -- biplav

我想知道一个简单的方法来解决Pang的评论,以及这如何影响性能(页面加载时间).非常感谢!

解决方案

关于问题1:使用JSON_HEX_TAG json_encode()

  • 示例1
    考虑一下这段简单的代码.

    <script>
        <?php $myVarValue = 'hello world'; ?>
        var myvar = <?php echo json_encode($myVarValue); ?>;
        alert(myvar);
    </script>
    

    输出:

    <script>
        var myvar = "hello world";
        alert(myvar);
    </script>
    

    它会警告hello world. 好.

  • 示例2
    让我们尝试使用</script>作为字符串.

    <script>
        <?php $myVarValue = '</script>'; ?>
        var myvar = <?php echo json_encode($myVarValue); ?>;
        alert(myvar);
    </script>
    

    输出:

    <script>
        var myvar = "<\/script>";
        alert(myvar);
    </script>
    

    它会提醒</script>. 好.

    如您所见,斜杠(/)正确转义为\/

  • 示例3
    现在,考虑以下非常特殊的字符串:<!--<script>

    <script>
        <?php $myVarValue = '<!--<script>'; ?>
        var myvar = <?php echo json_encode($myVarValue); ?>;
        alert(myvar);
    </script>
    

    输出:

    <script>
        var myvar = "<!--<script>";
        alert(myvar);
    </script>
    

    令人惊讶的是,它不会发出任何警报,并且错误控制台中没有任何内容. 什么?!

    如果您检查JSON的规范,则<!--<script>中的任何字符都无需转义,那么出了什么问题?

    json.org

  • 改编而成的图片

要获得完整且易于解释的答案,请阅读此惊人的问题与解答; A .简而言之,事实证明 <script>块中的<!--<script>混淆了HTML解析器. PHP实际上在json_encode()中正确地完成了它的工作; 即使它是一个完全有效的JavaScript字符串,您也只能在其中没有<!--<script>

我自己做了一些简单的测试.实际上,浏览器会忽略<!--<script>之后的所有内容,因此,如果发生在页面中间, 页面的整个后半部分都消失了!我不确定是否有人真的可以在其中注入恶意内容,例如执行任意操作 代码,但这已经够糟糕了.

  • 如果您不仅在$myVarValue中没有字符串,而且还拥有像array("key" => array("one", "and<!--<script>two", 3))这样的复杂对象(其中包括<!--<script>),那仍然很糟糕.
  • 如果您有一个普通的HTML文件(即没有PHP),并且在<script>块中的任何位置(甚至在JavaScript注释中)都有<!--<script>,那也很糟糕.
  • 如果您使用其他非PHP服务器端编程语言并生成了<!--<script>,那也很糟糕.
  • 如果您的PHP直接输出JavaScript(Content-type: application/javascript),则 [1] 没问题.

解决方案?使用 JSON_HEX_TAG 逃避<>(需要PHP 5.3.0).

<script>
    <?php $myVarValue = '<!--<script>'; ?>
    var myvar = <?php echo json_encode($myVarValue, JSON_HEX_TAG); ?>;
    //                                            ^^^^^^^^^^^^^^
    alert(myvar);
</script>

输出:

<script>
    var myvar = "\u003C!--\u003Cscript\u003E";
    alert(myvar);
</script>

它会警告<!--<script>. 万岁!

它之所以有效,是因为输出中没有更多的<!--<script>,因此也没有更多的HTML解析问题.

注意:您不需要 JSON_HEX_TAG ,如果您打印到<script>块中.

[1]在这里,确定"仅表示它没有<!--<script>问题.不建议动态生成外部JavaScript文件,因为它有很多缺点,例如此处此处.


关于问题2:初始页面加载时间

实际上,这很明显.如果获取$myVarValue值所需的时间很长 (例如,您正在从DB获取大量数据),PHP将必须等待,浏览器和用户也必须等待. 这意味着更长的初始页面加载时间.如果您稍后使用Ajax加载数据,它们将不会 等待看到初始结果,但是随后,Ajax调用将是一个额外的HTTP请求,因此它 意味着更多的服务器工作量和更多的网络负载.

当然,每种方法都有其优缺点,因此您必须决定.我建议阅读此出色的问题与解答; A .

I've read several posts about the question and found this to be the simplest solution, here is my code:

js inside PHP code

<script>
    <!--// 
      var jsBaseurl = <?php echo json_encode(BASE_URL."/"); ?>;
      var jsTitle = <?php echo json_encode($h1_title); ?>;
      var jsSubtl = <?php echo json_encode($h2_title);?>;
    //-->
</script>
<script src="external.js"></script>

and the external.js

var siteURL=jsBaseurl;
alert(siteURL+jsTitle+jsSubtl)

it works fine, my question is regarding to the following comments by Pang and biplav:

WARNING: This can kill your website. Example:

<?php $myVarValue = '<!--<script>'; ?>

See this question for details. Solution: Use JSON_HEX_TAG to escape < and > (requires PHP 5.3.0). - Pang

Another downside of this is that impacts the inital page load time. - biplav

I would like to know a simple solution for Pang's comment and how this all impacts the performance (page load time). Thanks a lot!

解决方案

About question 1: use JSON_HEX_TAG in json_encode()

  • Example 1
    Consider this simple piece of code.

    <script>
        <?php $myVarValue = 'hello world'; ?>
        var myvar = <?php echo json_encode($myVarValue); ?>;
        alert(myvar);
    </script>
    

    Output:

    <script>
        var myvar = "hello world";
        alert(myvar);
    </script>
    

    It alerts hello world. Good.

  • Example 2
    Let's try having </script> as the string.

    <script>
        <?php $myVarValue = '</script>'; ?>
        var myvar = <?php echo json_encode($myVarValue); ?>;
        alert(myvar);
    </script>
    

    Output:

    <script>
        var myvar = "<\/script>";
        alert(myvar);
    </script>
    

    It alerts </script>. Good.

    As you can see, the slash (/) is correctly escaped as \/,

  • Example 3
    Now, consider this very special string: <!--<script>

    <script>
        <?php $myVarValue = '<!--<script>'; ?>
        var myvar = <?php echo json_encode($myVarValue); ?>;
        alert(myvar);
    </script>
    

    Output:

    <script>
        var myvar = "<!--<script>";
        alert(myvar);
    </script>
    

    Surprisingly, it does not alert anything, and there's nothing in the error console. What?!

    If you check JSON's spec, none of the characters in <!--<script> need to be escaped, so what went wrong?

    Image adapted from json.org

For a complete and well explained answer, read this amazing Q & A. In short, it turns out that having <!--<script> in a <script> block confuses the HTML parser. PHP actually did its job correctly in json_encode(); you just can't have a <!--<script> there, even though it is a perfectly valid JavaScript string!

I did a few simple tests myself. The browsers actually ignore everything after <!--<script>, so if it happens in the middle of a page, the entire second half of the page is gone! I'm not sure if someone can actually inject something malicious there to, say, execute arbitrary code, but that's bad enough.

Also,

  • If you have not just a string in $myVarValue, but a complex object like array("key" => array("one", "and<!--<script>two", 3)), which includes <!--<script>, it's still bad.
  • If you have a plain HTML file (i.e. no PHP) and you have <!--<script> anywhere (even in a JavaScript comment) in your <script> block, it's also bad.
  • If you are using other, non-PHP, server-side programming languages, and produced <!--<script>, it's bad too.
  • If your PHP is outputting JavaScript directly (Content-type: application/javascript), it's actually ok [1].

The solution? Use JSON_HEX_TAG to escape < and > (requires PHP 5.3.0).

<script>
    <?php $myVarValue = '<!--<script>'; ?>
    var myvar = <?php echo json_encode($myVarValue, JSON_HEX_TAG); ?>;
    //                                            ^^^^^^^^^^^^^^
    alert(myvar);
</script>

Output:

<script>
    var myvar = "\u003C!--\u003Cscript\u003E";
    alert(myvar);
</script>

It alerts <!--<script>. Hurray!

It works because there's no more <!--<script> in the output, so no more HTML parsing problems.

Note: you don't need JSON_HEX_TAG if you're not printing into a <script> block.

[1] Here, "ok" merely means it is free from the <!--<script> issue. Dynamically generating external JavaScript files is not recommended as it has tons of disadvantages, such as those stated here, here, here.


About question 2: initial page load time

Actually, it's rather obvious. If the time needed to obtain the value of $myVarValue is long (e.g. you're fetching lots of data from DB), PHP will have to wait, so is the browser, and the user. That means longer initial page load time. If you load the data later with Ajax instead, they won't have to wait to see the initial result, but then, the Ajax call would be an extra HTTP request, so it means more workload to the server, and more load to the network.

Of course, each method has its pros and cons, so you have to decide. I suggest reading this excellent Q & A.

这篇关于将PHP变量传递到外部JavaScript(或jQuery)文件的最有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆