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

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

问题描述

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



我和一位同事正在考虑生成一个额外的Javascript PHP文件,只包含Javascript的所有变量。这种方式变量已经存在,并且HTML中没有额外的代码。



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

解决方案

一般数据传递



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

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

然后返回一个JavaScript对象文字,如下所示:

  {
test:var,
intvalue:1
}

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

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

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



输出到上标记的属性



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

 <?php 
$ nifty =我是nifty属性值,两者都是\\ 双和单引用。;
?>

...你可以像这样输出:



'pre> < DIV数据漂亮-ATTR = LT; PHP的回声用htmlspecialchars($漂亮)GT;? > ...< / DIV>

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



'pre> < DIV数据漂亮-ATTR = LT; =用htmlspecialchars($漂亮)GT;? > ...< / 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天全站免登陆