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

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

问题描述

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

我有这样的代码:

<?php$val = $myService->getValue();//进行 API 和数据库调用

在同一页面上,我的 JavaScript 代码需要将 $val 变量的值作为参数传递:

解决方案

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

无特定顺序:

  1. 使用 AJAX 从服务器获取您需要的数据.
  2. 将数据回显到页面某处,并使用 JavaScript 从 DOM 中获取信息.
  3. 将数据直接回显到 JavaScript.

在这篇文章中,我们将研究上述每种方法,并了解每种方法的优缺点,以及如何实现它们.

1.使用AJAX从服务器获取你需要的数据

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

优点

  • 更好的层间分离 - 如果您明天不再使用 PHP,并且想要转向 servlet、REST API 或其他一些服务,则您不必更改大部分 JavaScript代码.
  • 更具可读性 - JavaScript 是 JavaScript,PHP 是 PHP.如果不混合使用这两种语言,您可以获得两种语言的可读性更强的代码.
  • 允许异步数据传输 - 从 PHP 获取信息可能会耗费大量时间/资源.有时,您只是不想等待信息、加载页面并随时获取信息.
  • 无法直接在标记中找到数据 - 这意味着您的标记没有任何附加数据,只有 JavaScript 才能看到.

缺点

  • 延迟 - AJAX 创建一个 HTTP 请求,HTTP 请求通过网络传输并存在网络延迟.
  • 状态 - 通过单独的 HTTP 请求获取的数据不会包含来自获取 HTML 文档的 HTTP 请求的任何信息.您可能需要此信息(例如,如果 HTML 文档是为响应表单提交而生成的),并且如果您这样做,则必须以某种方式将其传输.如果您已经排除了在页面中嵌入数据的可能性(如果您使用这种技术,您就会有这种情况),那么这会将您限制在可能受到竞争条件影响的 cookie/会话中.

实现示例

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

get-data.php

/* 在这里做一些操作,比如与数据库对话,文件会话* 遥远的世界、地狱、闪光之城和加拿大.** AJAX 通常使用字符串,但您也可以输出 JSON、HTML 和 XML.* 这一切都取决于您使用 AJAX 发送的 Content-type 标头* 要求.*/回声 json_encode(42);//最后,您需要回显结果.//所有数据都应该是 json_encode()d.//你可以 json_encode() 任何 PHP 中的值,数组,字符串,//偶数对象.

index.php(或任何实际页面的名称)

<脚本>函数 reqListener() {控制台日志(this.responseText);}var oReq = 新 XMLHttpRequest();//新建请求对象oReq.onload = 函数(){//这是您处理如何处理响应的地方.//实际数据在 this.responseText 上找到警报(this.responseText);//将警报:42};oReq.open("get", "get-data.php", true);//^ 不要阻塞其余的执行.//不要等到请求完成//                                继续.oReq.send();<!-- 剪断-->

当文件加载完成时,上述两个文件的组合将提示42.

更多阅读材料

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

这种方法不如AJAX好用,但还是有它的优点的.从某种意义上说,PHP 和 JavaScript 之间仍然相对分离,JavaScript 中没有直接使用 PHP.

优点

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

缺点

  • 潜在的非语义标记 - 通常,发生的情况是您使用某种 来存储信息,因为这样更容易获得inputNode.value 之外的信息,但这样做意味着您的 HTML 中有一个毫无意义的元素.HTML 具有 <meta> 元素,用于存储有关文档的数据,HTML 5 引入了 data-* 属性,用于专门用于使用 JavaScript 读取的数据,这些数据可以与特定元素相关联.
  • 弄脏源 - PHP 生成的数据会直接输出到 HTML 源,这意味着您将获得一个更大但重点更少的 HTML 源.
  • 更难获得结构化数据 - 结构化数据必须是有效的 HTML,否则您必须自己转义和转换字符串.
  • 将 PHP 与您的数据逻辑紧密结合 - 因为 PHP 用于演示,所以您无法将两者完全分开.

实现示例

有了这个,我们的想法是创建某种不会向用户显示但对 JavaScript 可见的元素.

index.php

<div id="dom-target" style="display: none;"><?php$output = "42";//再次,做一些操作,得到输出.echo htmlspecialchars($output);/* 你必须逃跑,因为结果否则将不是有效的 HTML.*/?>

<脚本>var div = document.getElementById("dom-target");var myData = div.textContent;<!-- 剪断-->

3.将数据直接回显到 JavaScript

这可能是最容易理解的.

优点

  • 非常容易实施 - 实施和理解这一点几乎不需要什么.
  • 不污染源 - 变量直接输出到 JavaScript,因此 DOM 不受影响.

缺点

  • 将 PHP 与您的数据逻辑紧密结合 - 因为 PHP 用于演示,所以您无法将两者完全分开.

实现示例

实现相对简单:

<脚本>var data = <?php echo json_encode("42", JSON_HEX_TAG);?>;//不要忘记额外的分号!<!-- 剪断-->

祝你好运!

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?

I have code that looks like this:

<?php
$val = $myService->getValue(); // Makes an API and database call

On the same page, I have JavaScript code that needs the value of the $val variable to be passed as a parameter:

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

In no particular order:

  1. Use AJAX to get the data you need from the server.
  2. Echo the data into the page somewhere, and use JavaScript to get the information from the DOM.
  3. Echo the data directly to 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.

1. Use AJAX to get the data you need from the server

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

Pros

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

Cons

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

Implementation Example

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

get-data.php

/* 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 (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 -->

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

Some more reading material

2. Echo the data into the page somewhere, and use JavaScript to get the information from the DOM

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.

Pros

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

Cons

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

Implementation Example

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

index.php

<!-- 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. Echo the data directly to JavaScript

This is probably the easiest to understand.

Pros

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

Cons

  • Tightly couples PHP to your data logic - Because PHP is used in presentation, you can't separate the two cleanly.

Implementation Example

Implementation is relatively straightforward:

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

Good luck!

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

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