简体   繁体   English

在PHP变量中访问Javascript

[英]Accessing Javascript In PHP variable

I have a php variable of javascript code which was parsed from another page. 我有一个javascript代码的php变量,该变量是从另一个页面解析的。 Is there a simple way to access the javascript variables individually with php? 有没有一种简单的方法可以分别使用php访问javascript变量?

PHP: PHP:

$cool = "<script type='text/javascript'>
var Title = 'This is the title';
var Text = 'Some text here';

Title.info.showinfo({

    'thumb':'image.jpg',
    'date':'Oct 2',
    'year':'2011'

});
</script>";

What Im trying to accomplish: 我要完成的工作:

$title = "This is the title";
$text = "Some text here";
$thumb = "image.jpg";
$date = "Oct 2";
$year = "2011";

try something like this, 尝试这样的事情,

<?php
$data = array(
    'key1' => 'value1',
    'key2' => 'value2'
);
$str = "some string";
?>

then output it using JSON data format, 然后使用JSON数据格式输出

<script type='text/javascript'>
var data = <?php echo json_encode($data);?>;
var str = <?php echo json_encode($str);?>;

alert(data.key1); // value1
alert(str); // some string
</script>

It's not javascript yet. 还不是javascript。 It's just a piece of string. 这只是一条线。 And there's no simple way to get those values from PHP. 而且没有简单的方法可以从PHP获取这些值。 Some ways are. 有一些方法。

  1. Dive into the string(code) and get the values by explode()ing or pattern matching with regex. 深入研究字符串(代码),并通过explode()或与正则表达式进行模式匹配来获取值。

  2. Send the code to client first, let the javascript run and send back via AJAX. 首先将代码发送给客户端,让JavaScript运行并通过AJAX发送回去。

  3. If you have control of the javascript code, make the variables accessible by PHP in the first place. 如果您可以控制javascript代码,请首先使变量可被PHP访问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM