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

查看:68
本文介绍了如何将变量和数据从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 database call
?>

我有需要val的JavaScript代码,其外观类似于:

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

<script>
    myPlugin.start($val); // I tried this, but it 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 asynchronous 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请求获取的数据将不包含来自HTTP请求的获取HTML文档的任何信息.您可能需要此信息(例如,如果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(或任何实际的页面都这样命名)

<!-- 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.

此方法比AJAX逊色,但仍具有其优点.从某种意义上说,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>来存储信息,因为从inputNode.value中获取信息更容易,但是这样做意味着您的HTML中没有任何意义的元素. HTML具有用于文档数据的<meta>元素,HTML 5引入了用于数据的data-*属性,这些属性专门用于可与特定元素相关联的JavaScript读取.
  • 弄乱源代码-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 JavaScript 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.

  • 非常容易实现-只需很少的时间即可实现,并且理解.
  • 不弄脏源代码-变量直接输出到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与数据逻辑紧密结合-由于在演示文稿中使用了PHP,因此您无法将两者明确分开.
  • Tightly couples PHP to your data logic - Because PHP is used in presentation, you can't separate the two cleanly.

实施相对简单:

<!-- 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天全站免登陆