将 PHP 变量传递给 Javascript 的最佳方法是什么? [英] What's the best way to pass a PHP variable to Javascript?

查看:28
本文介绍了将 PHP 变量传递给 Javascript 的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前在隐藏的输入字段中回显某些变量,并在需要时使用 Javascript 读出它们.

我和一位同事现在正在考虑用 PHP 生成一个额外的 Javascript 文件,其中只包含 Javascript 的所有变量.这样,变量已经存在,HTML 中没有额外的代码.

将变量从 PHP 传递到 Javascript 的好方法是什么?我们的解决方案听起来如何?

解决方案

一般数据传递

JavaScript 常用的交换格式是 JSON,使用 json_encode.像这样的 PHP 文件:

 "var", "intvalue" => 1);回声 json_encode($data);?>

然后像这样返回一个 JavaScript 对象字面量:

<代码>{测试":变量",整数值":1}

您可以直接将其回显到页面上的 JavaScript 变量中,例如:

var data = ;

...或通过 Ajax 请求(例如使用 jQuery 的 getJSON).

输出到标签上的属性

如果您只需要将字符串输出到标签上的属性,请使用 htmlspecialchars.假设一个变量:

...你可以这样输出:

<div data-nifty-attr="<?php echo htmlspecialchars($nifty)?>">...</div>

...或者如果您使用短标签:

<div data-nifty-attr="<?= htmlspecialchars($nifty)?>">...</div>

I currently echo certain variables in hidden input fields and read them out with Javascript whenever I need them.

Me and a colleague are now thinking of generating an extra Javascript file with PHP which only contains all variables for Javascript. This way the variables already exist and there is no extra code in the HTML.

What are good ways to pass variables from PHP to Javascript? And how does our solution sound?

解决方案

General Data Passing

A commonly used exchange format for JavaScript is JSON, using json_encode. A PHP file like this:

<?php
    $data = array("test" => "var", "intvalue" => 1);
    echo json_encode($data);
?>

then returns a JavaScript object literal like this:

{
    "test" : "var",
    "intvalue" : 1
}

You can directly echo it into a JavaScript variable on your page, e.g.:

var data = <?php echo json_encode($data)?>;

...or request it via Ajax (e.g. using jQuery's getJSON).

Outputting to attributes on tags

If you just need to output a string to an attribute on a tag, use htmlspecialchars. Assuming a variable:

<?php
$nifty = "I'm the nifty attribute value with both "double" and 'single' quotes in it.";
?>

...you can output it like this:

<div data-nifty-attr="<?php echo htmlspecialchars($nifty)?>">...</div>

...or if you use short tags:

<div data-nifty-attr="<?= htmlspecialchars($nifty)?>">...</div>

这篇关于将 PHP 变量传递给 Javascript 的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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