如何将变量和数据从PHP传递给JavaScript? [英] How to pass variables and data from PHP to JavaScript?

查看:144
本文介绍了如何将变量和数据从PHP传递给JavaScript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在PHP中有一个变量,我需要在我的JavaScript代码中使用它的值。如何将我的变量从PHP变为JavaScript?

I have a variable in PHP, and I need its value in my JavaScript code. How can I get my variable from PHP to JavaScript?

我的代码如下所示:

<?php
     ...
     $val = $myService->getValue(); // makes an api and db call
?>

我的JavaScript代码需要 val 和看起来如下:

I have JavaScript code that needs val and looks along the lines of:

<script>
    myPlugin.start($val); // tried this, didn't work
    <?php myPlugin.start($val); ?> // this didn't work either
    myPlugin.start(<?=$val?> // this works sometimes, but sometimes it fails
</script>


推荐答案

实际上有几种方法可以做到这一点。有些方法比其他方法需要更多的开销,有些被认为比其他人好。

There are actually several approaches to do this. Some require more overhead than others, and some are considered better than others.

没有特别的顺序:


  1. 使用AJAX从服务器获取所需的数据。

  2. 将数据回传到页面某处,并使用JavaScript从DOM获取信息。

  3. 将数据直接回传给JavaScript。

在这篇文章中,我们将检查上述每种方法,并查看专业人士每个人的利弊,以及如何实现它们。

In this post, we'll examine each of the above methods, and see the pros and cons of each, as well as how to implement them.

这种方法被认为是最好的,因为您的服务器端和客户端脚本是完全独立的

This method is considered the best, because your server side and client side scripts are completely separate.


  • 更好的层间分离 - 如果明天你停止使用PHP,并希望转移到servlet,REST API或其他一些服务,您不必更改大部分JavaScript代码。

  • 更易读 - JavaScript是JavaScript,PHP是PHP。如果不混合这两种语言,您将获得两种语言的可读代码。

  • 允许异步数据传输 - 从PHP获取信息可能需要时间/资源。有时您只是不想等待信息,加载页面,并随时获取信息。

  • 标记上没有直接找到数据 - 这意味着您的标记保持清除任何其他数据,只有JavaScript才能看到它。

  • Better separation between layers - If tomorrow you stop using PHP, and want to move to a servlet, a REST API, or some other service, you don't have to change much of the JavaScript code.
  • More readable - JavaScript is JavaScript, PHP is PHP. Without mixing the two, you get more readable code on both languages.
  • Allows for async data transfer - Getting the information from PHP might be time/resources expensive. Sometimes you just don't want to wait for the information, load the page, and have the information reach whenever.
  • Data is not directly found on the markup - This means that your markup is kept clean of any additional data, and only JavaScript sees it.

  • 延迟 - AJAX创建HTTP请求,HTTP请求通过网络传输并具有网络延迟。

  • 状态 - 通过单独的HTTP请求获取的数据不包含来自获取HTML文档的HTTP请求的任何信息。您可能需要此信息(例如,如果HTML文档是为响应表单提交而生成的),如果您这样做,则必须以某种方式将其传输。如果您已排除在页面中嵌入数据(如果您使用此技术,那么这将限制您),那么这将限制您可能受竞争条件限制的cookie /会话。

  • Latency - AJAX creates an HTTP request, and HTTP requests are carried over network and have network latencies.
  • State - Data fetched via a separate HTTP request won't include any information from the HTTP request that fetched the HTML document. You may need this information (e.g. if the HTML document is generated in response to a form submission) and, if you do, will have to transfer it across somehow. If you have ruled out embedding the data in the page (which you have if you are using this technique) then that limits you to cookies/sessions which may be subject to race conditions.

使用AJAX,您需要两个页面,一个是PHP生成输出的地方,第二个是JavaScript的位置获得该输出:

With AJAX, you need two pages, one is where PHP generates the output, and the second is where JavaScript gets that output:

/* Do some operation here, like talk to the database, the file-session
 * The world beyond, limbo, the city of shimmers, and Canada.
 * 
 * AJAX generally uses strings, but you can output JSON, HTML and XML as well. 
 * It all depends on the Content-type header that you send with your AJAX
 * request. */

echo json_encode(42); //In the end, you need to echo the result. 
                      //All data should be json_encode()d.

                      //You can json_encode() any value in PHP, arrays, strings,
                      //even objects.



index.php(或任何实际页面命名为)



index.php (or whatever the actual page is named like)

<!-- snip -->
<script>
    function reqListener () {
      console.log(this.responseText);
    }

    var oReq = new XMLHttpRequest(); //New request object
    oReq.onload = function() {
        //This is where you handle what to do with the response.
        //The actual data is found on this.responseText
        alert(this.responseText); //Will alert: 42
    };
    oReq.open("get", "get-data.php", true);
    //                               ^ Don't block the rest of the execution.
    //                                 Don't wait until the request finishes to 
    //                                 continue.
    oReq.send();
</script>
<!-- snip -->

上述两个文件的组合将提醒 42 文件完成加载时。

The above combination of the two files will alert 42 when the file finishes loading.

  • Using XMLHttpRequest - MDN
  • XMLHttpRequest object reference - MDN
  • How do I return the response from an asynchronous call?

这种方法不如AJAX优先,但它仍然有其优点。在PHP和JavaScript之间仍然存在相对分开,因为JavaScript中没有PHP。

This method is less preferable to AJAX, but it still has its advantages. It's still relatively separated between PHP and JavaScript in a sense that there is no PHP directly in the JavaScript.


  • 快速 - DOM操作通常很快,您可以相对快速地存储和访问大量数据。

  • Fast - DOM operations are often quick, and you can store and access a lot of data relatively quickly.

  • 潜在的非语义标记 - 通常情况下,您使用某种< input type = hidden> 来存储信息,因为它更容易从<$ c $中获取信息c> inputNode.value ,但这样做意味着HTML中有一个无意义的元素。 HTML包含有关文档数据的< meta> 元素,HTML 5为数据引入了数据 - * 属性专门用于阅读可以与特定元素相关联的JS。

  • Dirties up the Source - PHP生成的数据直接输出到HTML源代码,这意味着你会得到一个更大,更少关注的HTML源代码。

  • 难以获得结构化数据 - 结构化数据必须是有效的HTML,否则你将不得不逃脱并且自己转换字符串。

  • 将PHP与数据逻辑紧密结合 - 因为在演示中使用了PHP,所以不能将这两者完全分开。

  • Potentially Unsemantic Markup - Usually, what happens is that you use some sort of <input type=hidden> to store the information, because it's easier to get the information out of inputNode.value, but doing so means that you have a meaningless element in your HTML. HTML has the <meta> element for data about the document, and HTML 5 introduces data-* attributes for data specifically for reading with JS that can be associated with particular elements.
  • Dirties up the Source - Data that PHP generates is outputted directly to the HTML source, meaning that you get a bigger and less focused HTML source.
  • Harder to get structured data - Structured data will have to be valid HTML, otherwise you'll have to escape and convert strings yourself.
  • Tightly couples PHP to your data logic - Because PHP is used in presentation, you can't separate the two cleanly.

有了这个,想法就是创造某种元素不会向用户显示,但对JavaScript可见。

With this, the idea is to create some sort of element which will not be displayed to the user, but is visible to JavaScript.

<!-- snip -->
<div id="dom-target" style="display: none;">
    <?php 
        $output = "42"; //Again, do some operation, get the output.
        echo htmlspecialchars($output); /* You have to escape because the result
                                           will not be valid HTML otherwise. */
    ?>
</div>
<script>
    var div = document.getElementById("dom-target");
    var myData = div.textContent;
</script>
<!-- snip -->



3。将数据直接回显到JavaScript



这可能是最容易理解的,也是最难用的。除非你知道自己在做什么,否则不要这样做。

3. Echo the data directly to JavaScript

This is probably the easiest to understand, and the most horrible to use. Don't do this unless you know what you're doing.


  • 非常容易实现 - 实现这一点很少,并且理解。

  • 不脏源 - 输出变量直接使用JavaScript,因此DOM不受影响。

  • Very easily implemented - It takes very little to implement this, and understand.
  • Does not dirty source - Variables are outputted directly to JavaScript, so the DOM is not affected.

  • 不安全 - PHP没有简单的JavaScript转义函数,它们实现起来并不容易。特别是在使用用户输入时,您非常容易受到第二层注入的攻击。 争议查看评论

  • 将PHP与数据逻辑紧密联系 - 因为PHP用于演示文稿,所以无法将两者分开干净利落。

  • 结构化数据很难 - 你可以做JSON ......有点儿。但XML和HTML需要特别注意。

  • Insecure - PHP has no trivial JavaScript escape functions, and they aren't trivial to implement. Especially when using user inputs, you are extremely vulnerable to second tier injections. Disputed see comments
  • Tightly couples PHP to your data logic - Because PHP is used in presentation, you can't separate the two cleanly.
  • Structured data is hard - You can probably do JSON... kinda. But XML and HTML will require special attention.

实施相对简单:

<!-- snip -->
<script>
    var data = <?php echo json_encode("42", JSON_HEX_TAG); ?>; //Don't forget the extra semicolon!
</script>
<!-- snip -->

祝你好运!

这篇关于如何将变量和数据从PHP传递给JavaScript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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